<?php
session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Logger.php';
require_once __DIR__ . '/../classes/Sales.php';

try {
    $database = new Database();
    $conn = $database->getConnection();
    $auth = new Auth($conn);
    $auth->requireLogin();

    $role = strtolower((string)($_SESSION['role'] ?? ''));
    if (!in_array($role, ['admin', 'super_admin'], true) && !$auth->isSuperAdmin($_SESSION['user_id'])) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Access denied.']);
        exit();
    }

    $reportId = (int)($_POST['report_id'] ?? 0);
    if ($reportId <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'A valid report ID is required.']);
        exit();
    }

    $branchStmt = $conn->prepare('SELECT branch_id FROM weekly_reports WHERE report_id = :report_id LIMIT 1');
    $branchStmt->execute([':report_id' => $reportId]);
    $notificationBranchId = (int)($_POST['notification_branch_id'] ?? $branchStmt->fetchColumn());
    if ($notificationBranchId <= 0) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Report was not found.']);
        exit();
    }

    $logger = new Logger($conn, $_SESSION['user_id'] ?? null, $_SESSION['username'] ?? '', $_SESSION['role'] ?? '');
    $sales = new Sales($conn, $logger);
    $sales->discardReport($reportId, $notificationBranchId);

    echo json_encode(['success' => true, 'message' => 'Report discarded.', 'report_id' => $reportId]);
} catch (Throwable $e) {
    error_log('Discard report failed: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>