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

$user_id = $_SESSION['user_id'] ?? null;
$actual_cash = isset($_POST['closing_cash']) ? floatval($_POST['closing_cash']) : 0.0;

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

// 1. Fetch the active shift for this user
$stmt = $conn->prepare("SELECT id, start_time, opening_cash FROM shifts WHERE user_id = ? AND end_time IS NULL LIMIT 1");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$shift = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$shift) {
    echo json_encode(['status' => 'error', 'message' => 'No active shift found']);
    exit;
}

$shift_id = $shift['id'];
$start_time = $shift['start_time'];
$opening_cash = floatval($shift['opening_cash']);

// 2. Sum of cash sales (IMPORTANT: use net_amount)
// 2. Sum of cash sales including tax
$sales_q = $conn->prepare("
    SELECT SUM(total_amount) AS cash_sales 
    FROM sales 
    WHERE shift_id = ? AND payment_method = 'cash'
");

$sales_q->bind_param("i", $shift_id);
$sales_q->execute();
$cash_sales = floatval($sales_q->get_result()->fetch_assoc()['cash_sales'] ?? 0.0);
$sales_q->close();

// 3. Sum of cash_in and cash_out from shift logs
$log_q = $conn->prepare("
    SELECT 
        SUM(CASE WHEN action_type = 'cash_in' THEN amount ELSE 0 END) AS cash_in,
        SUM(CASE WHEN action_type = 'cash_out' THEN amount ELSE 0 END) AS cash_out
    FROM shift_logs 
    WHERE shift_id = ?
");
$log_q->bind_param("i", $shift_id);
$log_q->execute();
$log_data = $log_q->get_result()->fetch_assoc();
$log_q->close();

$cash_in = floatval($log_data['cash_in'] ?? 0.0);
$cash_out = floatval($log_data['cash_out'] ?? 0.0);

// 4. Final expected cash calculation (no expenses)
$expected_cash = $opening_cash + $cash_sales + $cash_in - $cash_out;
$discrepancy = $actual_cash - $expected_cash;

// 5. Update the shift
$update = $conn->prepare("
    UPDATE shifts 
    SET end_time = NOW(),
        closing_cash = ?, 
        expected_cash = ?, 
        actual_cash = ?, 
        discrepancy = ?, 
        status = 'closed'
    WHERE id = ?
");
$update->bind_param("dddii", $actual_cash, $expected_cash, $actual_cash, $discrepancy, $shift_id);
$update->execute();

if ($update->affected_rows > 0) {
    // Return shift data for summary display
    echo json_encode([
        'status' => 'success',
        'shift_id' => $shift_id,
        'shift_data' => [
            'start_time' => $start_time,
            'end_time' => date('Y-m-d H:i:s'),
            'opening_cash' => $opening_cash,
            'closing_cash' => $actual_cash,
            'expected_cash' => $expected_cash,
            'actual_cash' => $actual_cash,
            'discrepancy' => $discrepancy,
            'cash_sales' => $cash_sales,
            'cash_in' => $cash_in,
            'cash_out' => $cash_out
        ]
    ]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Shift update failed']);
}
