<?php 
include 'header.php'; 

$user_id = $_SESSION['user_id'];
$branch_id = $_SESSION['branch_id'];

// جلب بيانات الوردية الحالية
$stmt = $pdo->prepare("SELECT * FROM shifts WHERE user_id = ? AND branch_id = ? AND status = 'open'");
$stmt->execute([$user_id, $branch_id]);
$shift = $stmt->fetch();

if (!$shift) { header("Location: pos.php"); exit(); }

// حساب إجمالي مبيعات الوردية دي فقط
$stmt_sales = $pdo->prepare("SELECT SUM(total_amount) FROM orders WHERE shift_id = ?");
$stmt_sales->execute([$shift['id']]);
$total_sales = $stmt_sales->fetchColumn() ?: 0;

if (isset($_POST['confirm_close'])) {
    $end_cash = $_POST['cash_end'];
    $stmt_close = $pdo->prepare("UPDATE shifts SET status = 'closed', end_time = CURRENT_TIMESTAMP, cash_end = ? WHERE id = ?");
    $stmt_close->execute([$end_cash, $shift['id']]);
    header("Location: dashboard.php");
    exit();
}
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-5">
            <div class="card shadow border-0 rounded-4">
                <div class="card-body p-4 text-center">
                    <h4 class="mb-4">إغلاق الوردية</h4>
                    <div class="alert alert-info py-3">
                        <div class="small">إجمالي مبيعاتك اليوم:</div>
                        <div class="h3 fw-bold"><?= number_format($total_sales, 2) ?> ج.م</div>
                    </div>
                    <form method="POST">
                        <div class="mb-3 text-start">
                            <label class="form-label fw-bold">المبلغ الفعلي الموجود في الدرج:</label>
                            <input type="number" name="cash_end" class="form-control form-control-lg" required placeholder="0.00">
                        </div>
                        <button type="submit" name="confirm_close" class="btn btn-danger w-100 py-3 fw-bold">تأكيد الإغلاق والخروج</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>