<?php
/**
 * Admin Records API for Dozar & Tripper
 * Provides JSON data for external integration (e.g. WasteMS)
 */

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

header('Content-Type: application/json');

// Simple API Hash Check
$api_hash = 'b02ebfd020139f0461a61faa767d2f12d39c25cdc76255b47c07cde79557197a';
$request_hash = $_GET['user_api_hash'] ?? '';

if ($request_hash !== $api_hash) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized API Access']);
    exit;
}

$pdo = getPDO();

// Get filter parameters
$current_bs = get_current_nepali_date();
$today_bs = sprintf('%04d-%02d-%02d', $current_bs['year'], $current_bs['month'], $current_bs['day']);

$report_type = $_GET['report_type'] ?? 'all'; // 'dozar', 'tripper', or 'all'
$date_from = $_GET['date_from'] ?? $today_bs;
$date_to = $_GET['date_to'] ?? $date_from;
$project_id = $_GET['project_id'] ?? '';
$vehicle_id = $_GET['vehicle_id'] ?? '';

$response = [
    'success' => true,
    'date_range' => ['from' => $date_from, 'to' => $date_to],
    'dozar_records' => [],
    'tripper_records' => []
];

// 1. Fetch Dozar Records
if ($report_type === 'all' || $report_type === 'dozar') {
    $where = "WHERE d.created_date BETWEEN ? AND ?";
    $params = [$date_from, $date_to];
    if ($project_id) {
        $where .= " AND d.project_id = ?";
        $params[] = $project_id;
    }
    if ($vehicle_id) {
        $where .= " AND d.vehicle_id = ?";
        $params[] = $vehicle_id;
    }

    $sql = "SELECT d.*, p.project_name, v.vehicle_number, dr.full_name as driver_name
            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
            $where ORDER BY d.created_at ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $response['dozar_records'] = $stmt->fetchAll();
}

// 2. Fetch Tripper Records
if ($report_type === 'all' || $report_type === 'tripper') {
    $where = "WHERE t.created_date BETWEEN ? AND ?";
    $params = [$date_from, $date_to];
    if ($project_id) {
        $where .= " AND t.project_id = ?";
        $params[] = $project_id;
    }
    if ($vehicle_id) {
        $where .= " AND t.vehicle_id = ?";
        $params[] = $vehicle_id;
    }

    $sql = "SELECT t.*, p.project_name, v.vehicle_number, dr.full_name as driver_name,
                   lc.full_name as loading_collector_name,
                   uc.full_name as unloading_collector_name
            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 users lc ON t.loading_collector_id = lc.id
            LEFT JOIN users uc ON t.unloading_collector_id = uc.id
            $where ORDER BY t.created_at ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $response['tripper_records'] = $stmt->fetchAll();
}

// Normalize for Swarnim Daily Report if requested
if (isset($_GET['normalize'])) {
    $normalized = [];
    foreach ($response['dozar_records'] as $r) {
        $hrs = $r['work_length_hours'] > 0 ? number_format($r['work_length_hours'], 1).' घन्टा' : '—';
        $km  = ($r['end_odometer'] > $r['start_odometer'])
               ? number_format($r['end_odometer'] - $r['start_odometer'], 1).' km' : '';
        $normalized[] = [
            'section'  => 'डोजर',
            'icon'     => '🚜',
            'color'    => '#92400e',
            'location' => trim($r['work_location'] ?: '—').($r['project_name'] ? ' ('.$r['project_name'].')' : ''),
            'qty'      => $hrs.($km ? ' · '.$km : '').($r['vehicle_number'] ? ' · '.$r['vehicle_number'] : ''),
            'leader'   => $r['collector_name'] ?: '—',
            'sup'      => $r['driver_name'] ?: '—',
            'remarks'  => $r['remarks'] ?: '',
        ];
    }
    $statusLabel = ['pending_unloading'=>'अनलोड बाँकी','completed'=>'पूर्ण','cancelled'=>'रद्द'];
    foreach ($response['tripper_records'] as $r) {
        $mat = $r['material_type'] ? $r['material_type'].' ' : '';
        $wt  = $r['quantity_weight'] > 0 ? number_format($r['quantity_weight'], 1).' kg' : '';
        $km_traveled = ($r['unloading_end_odometer'] > $r['loading_start_odometer']) 
            ? ($r['unloading_end_odometer'] - $r['loading_start_odometer']) : 0;
        $km  = $km_traveled > 0 ? number_format($km_traveled, 1).' km' : '';
        $normalized[] = [
            'section'  => 'ट्रिपर',
            'icon'     => '🚛',
            'color'    => '#6d28d9',
            'location' => ($r['loading_location'] ?: '—').' → '.($r['unloading_place'] ?: '—'),
            'qty'      => trim($mat.$wt.($km?' · '.$km:'').($r['vehicle_number']?' · '.$r['vehicle_number']:'')),
            'leader'   => $r['driver_name'] ?: '—',
            'sup'      => $statusLabel[$r['status']] ?? $r['status'],
            'remarks'  => trim(($r['loading_remarks'] ?: '').($r['unloading_remarks'] ? ' | '.$r['unloading_remarks'] : '')),
        ];
    }
    echo json_encode(['success' => true, 'records' => $normalized]);
} else {
    echo json_encode($response);
}
