<?php
// GET /api/reports/summary
// GET /api/reports/daily    ?date=2026-04-07
// GET /api/reports/monthly  ?month=04&year=2026
// GET /api/reports/export   ?type=daily&date=2026-04-07

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Method not allowed', 405);
}

// Determine sub-route from URI
$uri      = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($uri, '/'));
$subRoute = end($segments); // summary | daily | monthly | export

$db = getDB();

// ─── SUMMARY ─────────────────────────────────────────────────────────────────
if ($subRoute === 'summary') {
    $total      = $db->query("SELECT COUNT(*) AS c FROM meter_readings")->fetch_assoc()['c'];
    $totalUnits = $db->query("SELECT COALESCE(SUM(units),0) AS u FROM meter_readings")->fetch_assoc()['u'];
    $today      = $db->query("SELECT COUNT(*) AS c FROM meter_readings WHERE reading_date = CURDATE()")->fetch_assoc()['c'];
    $thisMonth  = $db->query("SELECT COUNT(*) AS c FROM meter_readings WHERE MONTH(reading_date)=MONTH(CURDATE()) AND YEAR(reading_date)=YEAR(CURDATE())")->fetch_assoc()['c'];
    $db->close();

    sendSuccess(['data' => [
        'total_readings'      => (int)$total,
        'total_units'         => (float)$totalUnits,
        'today_readings'      => (int)$today,
        'this_month_readings' => (int)$thisMonth,
    ]]);
}

// ─── DAILY ───────────────────────────────────────────────────────────────────
if ($subRoute === 'daily') {
    $date = $_GET['date'] ?? date('Y-m-d');

    $stmt = $db->prepare("
        SELECT r.id, u.name, u.employee_id,
               r.previous_reading AS previous, r.current_reading AS current,
               r.units, r.photo_path, r.note, r.reading_date AS date
        FROM meter_readings r
        JOIN users u ON u.id = r.user_id
        WHERE r.reading_date = ?
        ORDER BY r.created_at DESC
    ");
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $db->close();

    $rows = array_map(function ($r) {
        $r['photo_url'] = $r['photo_path'] ? UPLOAD_URL . $r['photo_path'] : null;
        unset($r['photo_path']);
        return $r;
    }, $rows);

    sendSuccess(['data' => $rows]);
}

// ─── MONTHLY ─────────────────────────────────────────────────────────────────
if ($subRoute === 'monthly') {
    $month = (int)($_GET['month'] ?? date('m'));
    $year  = (int)($_GET['year']  ?? date('Y'));

    $stmt = $db->prepare("
        SELECT reading_date AS date,
               COUNT(*) AS total_readings,
               SUM(units) AS total_units
        FROM meter_readings
        WHERE MONTH(reading_date) = ? AND YEAR(reading_date) = ?
        GROUP BY reading_date
        ORDER BY reading_date ASC
    ");
    $stmt->bind_param("ii", $month, $year);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $db->close();

    sendSuccess(['data' => $rows]);
}

// ─── EXPORT ──────────────────────────────────────────────────────────────────
if ($subRoute === 'export') {
    $type = $_GET['type'] ?? 'daily';
    $date = $_GET['date'] ?? date('Y-m-d');

    if ($type === 'daily') {
        $stmt = $db->prepare("
            SELECT u.name, u.employee_id,
                   r.previous_reading, r.current_reading, r.units,
                   r.reading_date, r.submitted_by, r.note
            FROM meter_readings r
            JOIN users u ON u.id = r.user_id
            WHERE r.reading_date = ?
            ORDER BY r.created_at DESC
        ");
        $stmt->bind_param("s", $date);
        $fileName = "daily_report_$date.csv";
    } else {
        // monthly
        $month = (int)($_GET['month'] ?? date('m'));
        $year  = (int)($_GET['year']  ?? date('Y'));
        $stmt  = $db->prepare("
            SELECT u.name, u.employee_id,
                   r.previous_reading, r.current_reading, r.units,
                   r.reading_date, r.submitted_by, r.note
            FROM meter_readings r
            JOIN users u ON u.id = r.user_id
            WHERE MONTH(r.reading_date) = ? AND YEAR(r.reading_date) = ?
            ORDER BY r.reading_date ASC
        ");
        $stmt->bind_param("ii", $month, $year);
        $fileName = "monthly_report_{$year}_{$month}.csv";
    }

    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $db->close();

    // Write CSV
    $exportDir = __DIR__ . '/../uploads/reports/';
    if (!is_dir($exportDir)) mkdir($exportDir, 0755, true);

    $filePath = $exportDir . $fileName;
    $fh = fopen($filePath, 'w');
    fputcsv($fh, ['Name', 'Employee ID', 'Previous', 'Current', 'Units', 'Date', 'Submitted By', 'Note']);
    foreach ($rows as $row) fputcsv($fh, array_values($row));
    fclose($fh);

    $fileUrl = BASE_URL . '/uploads/reports/' . $fileName;
    sendSuccess(['data' => ['file_url' => $fileUrl, 'file_name' => $fileName]]);
}

$db->close();
sendError('Unknown report type', 400);
