<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

// تعريف دالة esc للحماية
if (!function_exists('esc')) {
    function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
}

if (session_status() === PHP_SESSION_NONE) session_start();

// إعدادات اللغة
$lang = ($_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar')) === 'ar' ? 'ar' : 'en';
$_SESSION['lang'] = $lang;
$is_ar = $lang === 'ar';

$msg = '';
$err = '';

// معالجة البيانات المرسلة (Post-Redirect-Get)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'] ?? '';
    $amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;
    $desc = trim($_POST['description'] ?? '');

    if (!in_array($type, ['in', 'out'], true)) {
        $err = $is_ar ? 'النوع غير صالح' : 'Invalid transaction type';
    } elseif ($amount <= 0) {
        $err = $is_ar ? 'المبلغ يجب أن يكون أكبر من صفر' : 'Amount must be greater than zero';
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$type, $amount, $desc]);

            $_SESSION['add_balance_success'] = $is_ar ? '✅ تم تسجيل الحركة بنجاح' : '✅ Transaction recorded successfully';
            header('Location: add_balance.php?lang=' . $lang);
            exit;
        } catch (\Throwable $e) {
            $err = $e->getMessage();
        }
    }
}

if (!empty($_SESSION['add_balance_success'])) {
    $msg = $_SESSION['add_balance_success'];
    unset($_SESSION['add_balance_success']);
}
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'إضافة حركة نقدية' : 'Add Cash Transaction' ?> | Top Accessories</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2563eb;
            --success: #10b981;
            --danger: #ef4444;
            --bg: #f8fafc;
            --border: #e2e8f0;
            --card-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.08);
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg);
            color: #1e293b;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .bg-pattern {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;
            background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
            background-size: 30px 30px; opacity: 0.3;
        }

        .lux-container { width: 100%; max-width: 600px; }

        .premium-card {
            background: #ffffff;
            border-radius: 32px;
            padding: 40px;
            border: 1px solid var(--border);
            box-shadow: var(--card-shadow);
            position: relative;
            overflow: hidden;
        }

        .premium-card::before {
            content: ""; position: absolute; top: 0; left: 0; right: 0; height: 6px;
            background: linear-gradient(90deg, var(--success), var(--primary));
        }

        .header-box { text-align: center; margin-bottom: 35px; }
        .header-box h2 { font-weight: 800; font-size: 1.7rem; margin-bottom: 8px; }

        .type-selector {
            display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 30px;
        }
        .type-btn {
            border: 2px solid var(--border);
            border-radius: 18px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 700;
        }
        .type-btn i { display: block; font-size: 1.6rem; margin-bottom: 8px; }
        
        input[name="type"]:checked + .btn-in { border-color: var(--success); background: #f0fdf4; color: var(--success); }
        input[name="type"]:checked + .btn-out { border-color: var(--danger); background: #fef2f2; color: var(--danger); }

        .form-label { font-weight: 700; color: #64748b; font-size: 0.85rem; text-transform: uppercase; margin-bottom: 10px; }

        .lux-input {
            height: 56px; border-radius: 16px; border: 2px solid var(--border);
            padding: 0 18px; font-weight: 600; font-size: 1.1rem; transition: 0.3s;
        }
        .lux-input:focus { border-color: var(--primary); box-shadow: 0 0 0 5px rgba(37, 99, 235, 0.1); outline: none; }

        .btn-save {
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: 50px;
            padding: 16px;
            font-weight: 700;
            font-size: 1.1rem;
            width: 100%;
            margin-top: 20px;
            transition: 0.3s;
            box-shadow: 0 10px 20px -5px rgba(37, 99, 235, 0.3);
        }
        .btn-save:hover { transform: translateY(-2px); box-shadow: 0 15px 25px -5px rgba(37, 99, 235, 0.4); }

        .nav-btn {
            text-decoration: none; font-weight: 700; font-size: 0.85rem;
            color: #64748b; transition: 0.2s;
        }
        .nav-btn:hover { color: var(--primary); }

        .alert-custom { border-radius: 16px; border: none; font-weight: 600; }
    </style>
</head>
<body>

    <div class="bg-pattern"></div>

    <div class="lux-container">
        <!-- Top Navigation -->
        <div class="d-flex justify-content-between align-items-center mb-4 px-2">
            <a href="cash_report.php" class="nav-btn"><i class="fa fa-arrow-<?= $is_ar?'right':'left' ?> me-1"></i> <?= $is_ar?'التقارير المالية':'Cash Reports' ?></a>
            <div class="d-flex gap-3">
                <a href="index.php" class="nav-btn">🏠 <?= $is_ar?'الرئيسية':'Home' ?></a>
                <a href="?lang=<?= $is_ar?'en':'ar' ?>" class="nav-btn">🌐</a>
            </div>
        </div>

        <div class="premium-card">
            <div class="header-box">
                <h2><?= $is_ar ? 'تسجيل حركة مالية' : 'New Cash Entry' ?></h2>
                <p class="text-muted small"><?= $is_ar ? 'أدخل تفاصيل الإيداع أو السحب من الخزينة' : 'Record an inflow or outflow of cash' ?></p>
            </div>

            <?php if ($msg): ?>
                <div class="alert alert-success alert-custom p-3 mb-4 shadow-sm">
                    <i class="fa fa-check-circle me-2"></i> <?= esc($msg) ?>
                </div>
            <?php endif; ?>

            <?php if ($err): ?>
                <div class="alert alert-danger alert-custom p-3 mb-4 shadow-sm">
                    <i class="fa fa-exclamation-triangle me-2"></i> <?= esc($err) ?>
                </div>
            <?php endif; ?>

            <form method="post">
                <!-- اختيار النوع بأيقونات فخمة -->
                <div class="type-selector">
                    <label class="m-0">
                        <input type="radio" name="type" value="in" class="d-none" checked>
                        <div class="type-btn btn-in">
                            <i class="fa fa-arrow-down-long"></i>
                            <?= $is_ar ? 'إيداع (دخل)' : 'Cash In' ?>
                        </div>
                    </label>
                    <label class="m-0">
                        <input type="radio" name="type" value="out" class="d-none">
                        <div class="type-btn btn-out">
                            <i class="fa fa-arrow-up-long"></i>
                            <?= $is_ar ? 'سحب (مصروف)' : 'Cash Out' ?>
                        </div>
                    </label>
                </div>

                <div class="mb-4">
                    <label class="form-label"><?= $is_ar ? 'المبلغ المالي' : 'Transaction Amount' ?></label>
                    <div class="input-group">
                        <input type="number" step="0.01" name="amount" class="form-control lux-input text-center" placeholder="0.00" required autofocus>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="form-label"><?= $is_ar ? 'البيان / ملاحظات' : 'Description' ?></label>
                    <textarea name="description" class="form-control" style="border-radius: 16px; border: 2px solid var(--border); padding: 15px;" rows="3" placeholder="<?= $is_ar ? 'أدخل تفاصيل العملية...' : 'Enter transaction details...' ?>"></textarea>
                </div>

                <button type="submit" class="btn-save">
                    <i class="fa fa-save me-2"></i> <?= $is_ar ? 'تأكيد وحفظ الحركة' : 'Confirm & Save' ?>
                </button>
            </form>
        </div>

        <div class="text-center mt-5 text-muted small fw-bold">
            Top Accessories &bull; Financial Management Tool &copy; 2025
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>