<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/db.php';

// 🔐 Get token from Authorization header
$headers = getallheaders();
$token = $headers['Authorization'] ?? '';

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing token']);
    exit;
}

// 🔐 Validate token
$stmt = $pdo->prepare("SELECT * FROM users WHERE token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(403);
    echo json_encode(['error' => 'Invalid token']);
    exit;
}

// 📥 Get bill number from JSON body
$data = json_decode(file_get_contents("php://input"), true);
$bill_number = trim($data['bill_number'] ?? '');

if (!$bill_number) {
    http_response_code(400);
    echo json_encode(['error' => 'Bill number is required']);
    exit;
}

try {
    // 🔎 Check if bill exists
    $stmt = $pdo->prepare("SELECT status FROM bills WHERE bill_number = ?");
    $stmt->execute([$bill_number]);
    $bill = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$bill) {
        http_response_code(404);
        echo json_encode(['error' => 'Bill not found']);
        exit;
    }

    if ($bill['status'] === 'Complete') {
        echo json_encode(['message' => 'Bill already marked as Complete']);
        exit;
    }

    // ✅ Mark bill as complete
    $stmt = $pdo->prepare("UPDATE bills SET status = 'Complete', out_date = CURDATE() WHERE bill_number = ?");
    $stmt->execute([$bill_number]);

    echo json_encode([
        'success' => true,
        'message' => 'Bill marked as complete successfully'
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
