<?php
session_start();
require '../db.php';

$user_id = $_SESSION['user_id'] ?? null;
$store_id = $_SESSION['current_store_id'] ?? 1;

if (!$user_id) {
    echo json_encode(['status' => 'error', 'message' => 'User not found']);
    exit;
}

try {
    // Check for hold orders in the current store
    $stmt = $conn->prepare("
        SELECT 
            COUNT(*) as hold_count,
            SUM(total_amount) as total_hold_amount
        FROM hold_orders 
        WHERE store_id = ?
    ");
    $stmt->bind_param("i", $store_id);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $hold_count = intval($result['hold_count'] ?? 0);
    $total_hold_amount = floatval($result['total_hold_amount'] ?? 0);

    if ($hold_count > 0) {
        echo json_encode([
            'status' => 'error',
            'message' => "Cannot close shift. There are $hold_count hold order(s) with total amount of " . number_format($total_hold_amount, 2),
            'hold_count' => $hold_count,
            'total_hold_amount' => $total_hold_amount
        ]);
    } else {
        echo json_encode([
            'status' => 'success',
            'message' => 'No hold orders found. Shift can be closed.',
            'hold_count' => 0,
            'total_hold_amount' => 0
        ]);
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
