<?php
// export_data.php - Export data to CSV/Excel
session_name('FONFIX_SYSTEM_ID');
session_start();
require 'db.php';
require_once 'helpers.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    die("Access denied.");
}

$type = $_GET['type'] ?? 'jobs';
$format = $_GET['format'] ?? 'csv';
$startDate = $_GET['start'] ?? date('Y-m-01');
$endDate = $_GET['end'] ?? date('Y-m-d');
$branch = $_GET['branch'] ?? 'all';

// Security: Non-admins can only export their branch
if (!isAdmin() && isset($_SESSION['assigned_branch'])) {
    $branch = $_SESSION['assigned_branch'];
}

$filename = "fon2fix_export_{$type}_" . date('Y-m-d_His') . ".{$format}";

if ($format === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header("Content-Disposition: attachment; filename=\"$filename\"");
    $output = fopen('php://output', 'w');
    
    // Add BOM for Excel UTF-8 support
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
} else {
    // Excel format (tab-separated)
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header("Content-Disposition: attachment; filename=\"$filename\"");
    $output = fopen('php://output', 'w');
}

if ($type === 'jobs') {
    $sql = "SELECT job_id, branch, date, customer, phone, model, imei, repair, price, deposit, status, payment_status, payment_method, completed_at, pickup_date, warranty, remarks FROM jobs WHERE date BETWEEN ? AND ?";
    $params = [$startDate, $endDate];
    
    if ($branch !== 'all') {
        $sql .= " AND branch = ?";
        $params[] = $branch;
    }
    
    $sql .= " ORDER BY date DESC, job_id DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    // Headers
    fputcsv($output, ['Job ID', 'Branch', 'Date', 'Customer', 'Phone', 'Model', 'IMEI', 'Repair/Items', 'Price', 'Deposit', 'Status', 'Payment Status', 'Payment Method', 'Completed Date', 'Pickup Date', 'Warranty', 'Remarks']);
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($output, $row);
    }
    
} elseif ($type === 'stock') {
    $sql = "SELECT type, category, model_group, device_model, part_name, shortcode, cost, selling_price, supplier, stock_gombak, stock_sr FROM stock_list ORDER BY type, category, part_name";
    $stmt = $pdo->query($sql);
    
    fputcsv($output, ['Type', 'Category', 'Model Group', 'Device Model', 'Part Name', 'Shortcode', 'Cost', 'Selling Price', 'Supplier', 'Stock Gombak', 'Stock Sri Rampai']);
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($output, $row);
    }
    
} elseif ($type === 'customers') {
    $sql = "SELECT name, phone, (SELECT COUNT(*) FROM jobs WHERE jobs.phone = customers.phone) as total_orders, (SELECT SUM(price) FROM jobs WHERE jobs.phone = customers.phone AND status = 'Completed') as total_spent FROM customers ORDER BY name";
    $stmt = $pdo->query($sql);
    
    fputcsv($output, ['Name', 'Phone', 'Total Orders', 'Total Spent (RM)']);
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($output, $row);
    }
}

fclose($output);
exit;
?>
