<?php
require_once 'config/db.php';

// Check if fields were sent
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['fields'])) {
    header("Location: leads.php");
    exit;
}

$selected_fields = $_POST['fields'];
$search         = trim($_POST['search']       ?? '');
$filter_status  = $_POST['status_id']         ?? '';
$filter_source  = $_POST['source_id']         ?? '';
$filter_agent   = $_POST['agent_id']          ?? '';
$filter_project = trim($_POST['project_type'] ?? '');
$filter_from    = $_POST['date_from']         ?? '';
$filter_to      = $_POST['date_to']           ?? '';

$selected_ids = trim($_POST['selected_ids'] ?? '');

// Build query
$sql = "SELECT l.*, s.name as source_name, st.name as status_name, ag.name as agent_name
        FROM leads l
        LEFT JOIN lead_sources s   ON l.source_id         = s.id
        LEFT JOIN lead_statuses st ON l.status_id         = st.id
        LEFT JOIN sales_agents ag  ON l.assigned_agent_id = ag.id
        WHERE l.is_junk = 0";

$params = [];

if (!empty($selected_ids)) {
    // Export ONLY selected leads
    $id_array = array_map('intval', explode(',', $selected_ids));
    $placeholders = implode(',', array_fill(0, count($id_array), '?'));
    $sql .= " AND l.id IN ($placeholders)";
    $params = $id_array;
} else {
    // Export filtered leads
    if (!empty($search)) {
        $sql .= " AND (l.name LIKE ? OR l.phone LIKE ? OR l.email LIKE ?)";
        $p = "%$search%"; $params[] = $p; $params[] = $p; $params[] = $p;
    }
    if (!empty($filter_status))  { $sql .= " AND l.status_id = ?";       $params[] = $filter_status; }
    if (!empty($filter_source))  { $sql .= " AND l.source_id = ?";       $params[] = $filter_source; }
    if (!empty($filter_agent))   { 
        if($filter_agent === 'none') $sql .= " AND l.assigned_agent_id IS NULL";
        else { $sql .= " AND l.assigned_agent_id=?"; $params[] = $filter_agent; }
    }
    if (!empty($filter_project)) { $sql .= " AND l.project_type LIKE ?"; $params[] = "%$filter_project%"; }
    if (!empty($filter_from))    { $sql .= " AND DATE(l.created_at) >= ?"; $params[] = $filter_from; }
    if (!empty($filter_to))      { $sql .= " AND DATE(l.created_at) <= ?"; $params[] = $filter_to; }
}

$sql .= " ORDER BY l.created_at DESC";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $leads = $stmt->fetchAll();

    // Prepare CSV
    $filename = "leads_export_" . date('Y-m-d_His') . ".csv";
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $filename);
    
    $output = fopen('php://output', 'w');
    
    // Add UTF-8 BOM for Excel
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

    // Headers mapped from field values
    $header_map = [
        'phone'        => 'Phone / Contact',
        'name'         => 'Name',
        'email'        => 'Email',
        'status'       => 'Pipeline Status',
        'source'       => 'Lead Source',
        'agent'        => 'Assigned Agent',
        'project_type' => 'Project Type',
        'building_name'=> 'Building / Door No',
        'area'         => 'Area / Street',
        'city'         => 'City',
        'district'     => 'District',
        'pincode'      => 'Pincode',
        'state'        => 'State',
        'created_at'   => 'Date Added',
        'notes'        => 'Internal Notes'
    ];

    $csv_headers = [];
    foreach ($selected_fields as $field) {
        if (isset($header_map[$field])) {
            $csv_headers[] = $header_map[$field];
        } else {
            // handle raw fields if any
            $csv_headers[] = ucfirst(str_replace('_', ' ', $field));
        }
    }
    fputcsv($output, $csv_headers);

    // Data
    foreach ($leads as $lead) {
        $row = [];
        foreach ($selected_fields as $field) {
            switch ($field) {
                case 'phone':        $row[] = $lead['phone']; break;
                case 'name':         $row[] = $lead['name'] ?? '-'; break;
                case 'email':        $row[] = $lead['email'] ?? '-'; break;
                case 'status':       $row[] = $lead['status_name'] ?? 'New'; break;
                case 'source':       $row[] = $lead['source_name'] ?? 'Direct'; break;
                case 'agent':        $row[] = $lead['agent_name'] ?? 'Unassigned'; break;
                case 'project_type': $row[] = $lead['project_type'] ?? '-'; break;
                case 'building_name':$row[] = $lead['building_name'] ?? '-'; break;
                case 'area':         $row[] = $lead['area'] ?? '-'; break;
                case 'city':         $row[] = $lead['city'] ?? '-'; break;
                case 'district':     $row[] = $lead['district'] ?? '-'; break;
                case 'pincode':      $row[] = $lead['pincode'] ?? '-'; break;
                case 'state':        $row[] = $lead['state'] ?? '-'; break;
                case 'created_at':   $row[] = date('d M Y h:i A', strtotime($lead['created_at'])); break;
                case 'notes':        $row[] = $lead['notes'] ?? ''; break;
                default:             $row[] = $lead[$field] ?? '-'; break;
            }
        }
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit;

} catch (PDOException $e) {
    echo "Export Error: " . $e->getMessage();
}
