<?php
require_once '../config/db.php';
session_start();

// Ensure agent is logged in
if (!isset($_SESSION['agent_id'])) {
    header("Location: ../login.php");
    exit;
}

$agent_id = $_SESSION['agent_id'];

// Check if fields were sent
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $_SERVER['REQUEST_METHOD'] !== 'GET') {
    header("Location: my_leads.php");
    exit;
}

$selected_fields = $_POST['fields'] ?? $_GET['fields'] ?? ['phone','name','email','status','project_type','created_at'];
$search         = trim($_POST['search']       ?? $_GET['search']       ?? '');
$filter_stage   = $_POST['status_id']         ?? $_GET['status_id']    ?? '';
$filter_from    = $_POST['date_from']         ?? $_GET['date_from']    ?? '';
$filter_to      = $_POST['date_to']           ?? $_GET['date_to']      ?? '';
$selected_ids   = trim($_POST['selected_ids'] ?? $_GET['selected_ids'] ?? '');

// Build query
$sql = "SELECT l.*, st.name as status_name
        FROM leads l
        LEFT JOIN lead_statuses st ON l.status_id = st.id
        WHERE l.assigned_agent_id = ? AND l.is_junk = 0";

$params = [$agent_id];

if (!empty($selected_ids)) {
    // Export ONLY selected leads (still checking agent_id for security)
    $id_array = array_map('intval', explode(',', $selected_ids));
    $placeholders = implode(',', array_fill(0, count($id_array), '?'));
    $sql .= " AND l.id IN ($placeholders)";
    // params already has agent_id, append the rest
    foreach($id_array as $id) $params[] = $id;
} else {
    // Export filtered leads
    if (!empty($search)) {
        $sql .= " AND (l.name LIKE ? OR l.phone LIKE ?)";
        $p = "%$search%"; $params[] = $p; $params[] = $p;
    }
    if (!empty($filter_stage)) { $sql .= " AND l.status_id = ?"; $params[] = $filter_stage; }
    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 = "my_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');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM for Excel

    $header_map = [
        'phone'        => 'Phone / Contact',
        'name'         => 'Name',
        'email'        => 'Email',
        'status'       => 'Pipeline Status',
        'project_type' => 'Project Type',
        'created_at'   => 'Date Added',
        'notes'        => 'Internal Notes'
    ];

    $csv_headers = [];
    foreach ($selected_fields as $field) {
        $csv_headers[] = $header_map[$field] ?? ucfirst(str_replace('_', ' ', $field));
    }
    fputcsv($output, $csv_headers);

    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 'project_type': $row[] = $lead['project_type'] ?? '-'; 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();
}
