<?php
require_once 'includes/auth.php';
require_once 'includes/config.php';
require 'vendor/autoload.php';
checkRole(['superadmin', 'developer']);

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if(!isset($_GET['start_date']) || !isset($_GET['end_date']) || !isset($_GET['status'])) {
    $_SESSION['error'] = "Semua field harus diisi!";
    header("Location: dashboard.php");
    exit();
}

try {
    $mkt_pdo = new PDO("mysql:host=$host;dbname=db_callv3mkt", $username, $password);
    $mkt_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $start_date = $_GET['start_date'];
    $end_date = $_GET['end_date'];
    $status = $_GET['status'];
    
    $query = "SELECT 
        d.phone_number as target_number,
        d.pressed_button,
        CASE 
            WHEN d.status = 'Success' THEN 'Followed Up'
            ELSE 'Pending'
        END as status,
        d.nd_status,
        d.whatsapp_clicked_at as call_duration,
        d.note as followup_notes,
        m.nama_lengkap as marketing_name,
        d.original_call_date
    FROM distributed_numbers d
    LEFT JOIN db_callv3sa.marketing m ON d.marketing_id = m.id
    WHERE DATE(d.original_call_date) BETWEEN :start_date AND :end_date
    AND CASE 
        WHEN :status = '1' THEN d.status = 'Success'
        ELSE d.status != 'Success'
    END
    ORDER BY d.original_call_date DESC";
    
    $stmt = $mkt_pdo->prepare($query);
    $stmt->bindParam(':start_date', $start_date);
    $stmt->bindParam(':end_date', $end_date);
    $stmt->bindParam(':status', $status);
    $stmt->execute();
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if(empty($data)) {
        $_SESSION['error'] = "Tidak ada data untuk kriteria yang dipilih";
        header("Location: dashboard.php");
        exit();
    }

    // Bersihkan output buffer
    if (ob_get_length()) ob_end_clean();

    // Nonaktifkan output buffering
    ob_start();

    // Buat spreadsheet baru
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    
    // Set header style
    $headerStyle = [
        'font' => ['bold' => true],
        'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'color' => ['rgb' => 'E0E0E0']]
    ];
    
    // Set header
    $headers = [
        'Target Number', 
        'Pressed Button', 
        'Status',
        'ND Status',
        'Call Duration', 
        'Followup Notes', 
        'Marketing',
        'Original Call Date'
    ];
    foreach (range('A', 'H') as $key => $col) {
        $sheet->setCellValue($col.'1', $headers[$key]);
        $sheet->getStyle($col.'1')->applyFromArray($headerStyle);
    }

    // Isi data
    $row = 2;
    foreach($data as $item) {
        // Format nomor telepon agar tidak menjadi notasi ilmiah
        $phone = "'".$item['target_number']; // Tambahkan single quote di depan nomor
        
        $sheet->setCellValue('A'.$row, $phone);
        $sheet->setCellValue('B'.$row, $item['pressed_button']);
        $sheet->setCellValue('C'.$row, $item['status']);
        $sheet->setCellValue('D'.$row, $item['nd_status']);
        $sheet->setCellValue('E'.$row, $item['call_duration']);
        $sheet->setCellValue('F'.$row, $item['followup_notes']);
        $sheet->setCellValue('G'.$row, $item['marketing_name']);
        $sheet->setCellValue('H'.$row, $item['original_call_date']);
        $row++;
    }

    // Auto size kolom
    foreach(range('A','H') as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
    }

    // Set nama file
    $filename = "MKT_Report_".($status == 1 ? 'FollowedUp' : 'Pending')."_".$start_date."_".$end_date.".xlsx";

    // Set header untuk download
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header('Cache-Control: max-age=0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    // Output file
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');

    // Bersihkan buffer dan hentikan eksekusi
    ob_end_flush();
    exit;
    
} catch(PDOException $e) {
    error_log("Error in MKT report: " . $e->getMessage());
    $_SESSION['error'] = "Terjadi kesalahan: " . $e->getMessage();
    header("Location: dashboard.php");
    exit();
} 