<?php
/**
 * Export Reports to CSV
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

$user = getCurrentUser();
if (!$user) {
    header('Location: ' . SITE_URL . '/login.php');
    exit;
}

$pdo = getPDO();

// Get parameters
$report_type = sanitize($_GET['report_type'] ?? 'dozar');
$date_from = sanitize($_GET['date_from'] ?? date('Y-m-01'));
$date_to = sanitize($_GET['date_to'] ?? date('Y-m-d'));
$project_id = sanitize($_GET['project_id'] ?? '');

// Get user's assigned projects
$projectFilter = '';
$params = [];
if ($user['role'] !== 'admin' && $user['role'] !== 'viewer' && $user['assigned_projects']) {
    $projectIds = explode(',', $user['assigned_projects']);
    $placeholders = implode(',', array_fill(0, count($projectIds), '?'));
    $projectFilter = " AND project_id IN ($placeholders)";
    $params = $projectIds;
}

// Add project filter
if ($project_id) {
    $projectFilter .= " AND project_id = ?";
    $params[] = $project_id;
}

// Generate filename
$filename = $report_type . '_report_' . $date_from . '_to_' . $date_to . '.csv';

// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');

// Create output handle
$output = fopen('php://output', 'w');

// Write BOM for UTF-8 support
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

if ($report_type === 'dozar') {
    // Dozar CSV headers
    fputcsv($output, [
        'Date',
        'Project',
        'Vehicle Number',
        'Driver',
        'Deployed From',
        'Work Location',
        'Start Odometer',
        'End Odometer',
        'Work Hours',
        'Start Time',
        'End Time',
        'Group',
        'Remarks'
    ]);
    
    // Get dozar records
    $sql = "SELECT d.created_date, p.project_name, v.vehicle_number, dr.full_name as driver_name,
            df.entity_name as deployed_name, d.work_location, d.start_odometer, d.end_odometer,
            d.work_length_hours, d.start_time, d.end_time, g.group_name, d.remarks
            FROM dozar_records d
            LEFT JOIN projects p ON d.project_id = p.id
            LEFT JOIN vehicles v ON d.vehicle_id = v.id
            LEFT JOIN drivers dr ON d.driver_id = dr.id
            LEFT JOIN deployed_from df ON d.deployed_from_id = df.id
            LEFT JOIN groups g ON d.group_id = g.id
            WHERE d.created_date BETWEEN ? AND ? $projectFilter
            ORDER BY d.created_date DESC";
    
    $params = array_merge([$date_from, $date_to], $params);
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $records = $stmt->fetchAll();
    
    foreach ($records as $row) {
        fputcsv($output, [
            $row['created_date'],
            $row['project_name'],
            $row['vehicle_number'],
            $row['driver_name'],
            $row['deployed_name'],
            $row['work_location'],
            $row['start_odometer'],
            $row['end_odometer'],
            $row['work_length_hours'],
            $row['start_time'],
            $row['end_time'],
            $row['group_name'],
            $row['remarks']
        ]);
    }
    
} else {
    // Tripper CSV headers
    fputcsv($output, [
        'Date',
        'Project',
        'Vehicle Number',
        'Driver',
        'Deployed From',
        'Work Location',
        'Loading Location',
        'Unloading Place',
        'Start Odometer',
        'End Odometer',
        'Total KM',
        'Material Type',
        'Quantity',
        'Status',
        'Group',
        'Loading Remarks',
        'Unloading Remarks'
    ]);
    
    // Get tripper records
    $sql = "SELECT t.created_date, p.project_name, v.vehicle_number, dr.full_name as driver_name,
            df.entity_name as deployed_name, t.work_location, t.loading_location, t.unloading_place,
            t.loading_start_odometer, t.unloading_end_odometer, t.material_type, t.quantity_weight,
            t.status, g.group_name, t.loading_remarks, t.unloading_remarks
            FROM tripper_records t
            LEFT JOIN projects p ON t.project_id = p.id
            LEFT JOIN vehicles v ON t.vehicle_id = v.id
            LEFT JOIN drivers dr ON t.driver_id = dr.id
            LEFT JOIN deployed_from df ON t.deployed_from_id = df.id
            LEFT JOIN groups g ON t.group_id = g.id
            WHERE t.created_date BETWEEN ? AND ? $projectFilter
            ORDER BY t.created_date DESC";
    
    $params = array_merge([$date_from, $date_to], $params);
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $records = $stmt->fetchAll();
    
    foreach ($records as $row) {
        $total_km = $row['unloading_end_odometer'] ? $row['unloading_end_odometer'] - $row['loading_start_odometer'] : 0;
        fputcsv($output, [
            $row['created_date'],
            $row['project_name'],
            $row['vehicle_number'],
            $row['driver_name'],
            $row['deployed_name'],
            $row['work_location'],
            $row['loading_location'],
            $row['unloading_place'],
            $row['loading_start_odometer'],
            $row['unloading_end_odometer'],
            $total_km,
            $row['material_type'],
            $row['quantity_weight'],
            $row['status'],
            $row['group_name'],
            $row['loading_remarks'],
            $row['unloading_remarks']
        ]);
    }
}

fclose($output);
exit;
