<?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'])) {
    $_SESSION['error'] = "Tanggal 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'];
    
    $query = "SELECT 
        d.original_call_date,
        d.phone_number as target_number,
        d.pressed_button,
        d.status,
        d.note,
        s.nama_lengkap as supervisor_name,
        m.nama_lengkap as marketing_name
    FROM distributed_numbers d
    LEFT JOIN db_callv3sa.marketing m ON d.marketing_id = m.id
    LEFT JOIN db_callv3sa.supervisor s ON m.supervisor_id = s.id
    WHERE DATE(d.original_call_date) BETWEEN :start_date AND :end_date
    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->execute();
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if(empty($data)) {
        $_SESSION['error'] = "Tidak ada data untuk periode 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 = ['Original Call Date', 'Target Number', 'Pressed Button', 'Status', 'Note', 'Supervisor', 'Marketing'];
    foreach (range('A', 'G') as $key => $col) {
        $sheet->setCellValue($col.'1', $headers[$key]);
        $sheet->getStyle($col.'1')->applyFromArray($headerStyle);
    }

    // Isi data
    $row = 2;
    foreach($data as $item) {
        $sheet->setCellValue('A'.$row, $item['original_call_date']);
        $sheet->setCellValue('B'.$row, $item['target_number']);
        $sheet->setCellValue('C'.$row, $item['pressed_button']);
        $sheet->setCellValue('D'.$row, $item['status']);
        $sheet->setCellValue('E'.$row, $item['note']);
        $sheet->setCellValue('F'.$row, $item['supervisor_name']);
        $sheet->setCellValue('G'.$row, $item['marketing_name']);
        $row++;
    }

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

    // Set nama file
    $filename = "SPV_Report_".$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 SPV report: " . $e->getMessage());
    $_SESSION['error'] = "Terjadi kesalahan: " . $e->getMessage();
    header("Location: dashboard.php");
    exit();
} 