<?php
/**
 * EXPORT TO CSV - KEPATUHAN PEMBAYARAN
 * Direct server-side export without API dependency
 */

declare(strict_types=1);

session_start();

require_once '../../config/connection.php';
require_once '../../config/session.php';

// Check authentication
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    die('Unauthorized access');
}

/* ================= DATABASE CLASS ================= */
class Database {
    private mysqli $conn;
    
    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            throw new Exception('Koneksi database gagal: ' . $this->conn->connect_error);
        }
        $this->conn->set_charset('utf8mb4');
    }
    
    public function prepare(string $query): mysqli_stmt|false { 
        return $this->conn->prepare($query); 
    }
    
    public function close(): void { 
        $this->conn->close(); 
    }
}

/* ================= HELPER FUNCTIONS ================= */
function persen(float $capaian, float $target): float {
    return $target > 0 ? round(($capaian / $target) * 100, 2) : 0.0;
}

function kategori(float $persen): string {
    if ($persen >= 95) return 'EXCELLENT';
    if ($persen >= 85) return 'GOOD';
    if ($persen >= 70) return 'AVERAGE';
    return 'POOR';
}

/* ================= MAIN EXPORT LOGIC ================= */
try {
    $period = trim($_GET['period'] ?? '');
    
    if (empty($period)) {
        die('Period parameter is required');
    }
    
    $db = new Database();
    
    // Get data from database
    $stmt = $db->prepare("
        SELECT 
            TRIM(ta) ta, 
            UPPER(TRIM(category)) category,
            SUM(target) target, 
            SUM(capaian) capaian
        FROM kepatuhan_pembayaran
        WHERE TRIM(period) = ?
          AND UPPER(TRIM(month)) = 'TOTAL'
        GROUP BY ta, category
        ORDER BY category, ta
    ");
    
    $stmt->bind_param("s", $period);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Prepare CSV export
    $filename = 'Kepatuhan_' . str_replace(' ', '_', $period) . '_' . date('Ymd_His') . '.csv';
    
    // Set headers for CSV download
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    
    // Open output stream
    $output = fopen('php://output', 'w');
    
    // Add UTF-8 BOM for Excel compatibility
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // Write header rows
    fputcsv($output, ['KEPATUHAN PEMBAYARAN']);
    fputcsv($output, ['Periode: ' . $period]);
    fputcsv($output, ['Tanggal Export: ' . date('d/m/Y H:i:s')]);
    fputcsv($output, []); // Empty row
    
    // Write column headers
    fputcsv($output, [
        'NO', 
        'TA/SEKOLAH', 
        'CATEGORY', 
        'TARGET', 
        'CAPAIAN', 
        'PIUTANG', 
        'PERSEN (%)', 
        'KATEGORI'
    ]);
    
    // Write data rows
    $no = 1;
    while ($row = $result->fetch_assoc()) {
        $target = (float)$row['target'];
        $capaian = (float)$row['capaian'];
        $piutang = $target - $capaian;
        $persen_val = persen($capaian, $target);
        
        fputcsv($output, [
            $no++,
            $row['ta'],
            $row['category'],
            number_format($target, 2, '.', ''),
            number_format($capaian, 2, '.', ''),
            number_format($piutang, 2, '.', ''),
            number_format($persen_val, 2, '.', ''),
            kategori($persen_val)
        ]);
    }
    
    fclose($output);
    $db->close();
    exit;
    
} catch (Exception $e) {
    error_log('Export Error: ' . $e->getMessage());
    die('Export failed: ' . $e->getMessage());
}