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

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 = '';

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

    if ($amount <= 0) {
        $err = $is_ar ? 'المبلغ يجب أن يكون أكبر من صفر' : 'Amount must be greater than zero';
    } else {
        try {
            $category = 'expense'; // افتراضي

            if ($type === 'profit') {
                $monthName = date('F Y');
                $desc = ($desc ? $desc . ' - ' : '') . ($is_ar ? "سحب أرباح لشهر $monthName" : "Profit Withdrawal - $monthName");
                $category = 'profit_withdrawal'; // ← التعديل هنا
            }

            // ← التعديل: أضفنا category
            $stmt = $pdo->prepare("INSERT INTO cash_transactions (type, amount, description, category, created_at) VALUES ('out', ?, ?, ?, NOW())");
            $stmt->execute([$amount, $desc, $category]);

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

if (!empty($_SESSION['withdraw_success'])) {
    $msg = $_SESSION['withdraw_success'];
    unset($_SESSION['withdraw_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 ? 'سحب الأرباح' : 'Withdraw Profits' ?> | 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;
            --danger: #f43f5e;
            --success: #10b981;
            --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, #6366f1, var(--danger));
        }

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

        .withdraw-type-grid {
            display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 30px;
        }
        .type-option {
            border: 2px solid var(--border);
            border-radius: 20px;
            padding: 20px 10px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
        }
        .type-option i { display: block; font-size: 1.7rem; margin-bottom: 10px; opacity: 0.7; }
        .type-option span { font-weight: 800; font-size: 0.95rem; }

        input[name="withdraw_type"]:checked + .type-option {
            border-color: var(--danger);
            background: #fff1f2;
            color: var(--danger);
            transform: translateY(-5px);
            box-shadow: 0 15px 30px -10px rgba(244, 63, 94, 0.2);
        }
        input[name="withdraw_type"]:checked + .type-option i { opacity: 1; }

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

        .lux-input {
            height: 60px; border-radius: 18px; border: 2px solid var(--border);
            padding: 0 20px; font-weight: 800; font-size: 1.4rem; transition: 0.3s;
            color: var(--danger);
        }
        .lux-input:focus { border-color: var(--danger); box-shadow: 0 0 0 6px rgba(244, 63, 94, 0.1); outline: none; }

        .btn-confirm {
            background: var(--danger);
            color: #fff;
            border: none;
            border-radius: 50px;
            padding: 18px;
            font-weight: 800;
            font-size: 1.15rem;
            width: 100%;
            margin-top: 25px;
            transition: 0.3s;
            box-shadow: 0 12px 25px -5px rgba(244, 63, 94, 0.3);
        }
        .btn-confirm:hover { transform: translateY(-3px); background: #e11d48; box-shadow: 0 20px 30px -5px rgba(244, 63, 94, 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-lux { border-radius: 18px; border: none; font-weight: 700; box-shadow: 0 4px 10px rgba(0,0,0,0.03); }
    </style>
</head>
<body>

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

    <div class="lux-container">
        <!-- 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?'التقارير المالية':'Financial 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 ? 'سحب نقدية من الخزينة' : 'Withdrawal Portal' ?></h2>
                <p class="text-muted small"><?= $is_ar ? 'اختر تصنيف "سحب أرباح" لتوثيق سحوبات الشركاء' : 'Select "Profits" to document partner withdrawals' ?></p>
            </div>

            <?php if ($msg): ?>
                <div class="alert alert-success alert-lux 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-lux p-3 mb-4 shadow-sm">
                    <i class="fa fa-exclamation-triangle me-2"></i> <?= esc($err) ?>
                </div>
            <?php endif; ?>

            <form method="post">
                <!-- اختيار نوع السحب -->
                <label class="form-label"><?= $is_ar ? 'ما هو نوع هذا السحب؟' : 'Withdrawal Category' ?></label>
                <div class="withdraw-type-grid">
                    <label class="m-0">
                        <input type="radio" name="withdraw_type" value="normal" class="d-none" checked>
                        <div class="type-option">
                            <i class="fa fa-receipt"></i>
                            <span><?= $is_ar ? 'سحب مصاريف' : 'Expenses' ?></span>
                        </div>
                    </label>
                    <label class="m-0">
                        <input type="radio" name="withdraw_type" value="profit" class="d-none">
                        <div class="type-option" style="border-color: #6366f1; color: #6366f1; background: #eef2ff;">
                            <i class="fa fa-vault"></i>
                            <span><?= $is_ar ? 'سحب أرباح' : 'Withdraw Profits' ?></span>
                        </div>
                    </label>
                </div>

                <div class="mb-4">
                    <label class="form-label"><?= $is_ar ? 'المبلغ المراد سحبه' : 'Amount to Withdraw' ?></label>
                    <input type="number" step="0.01" name="amount" class="form-control lux-input text-center" placeholder="0.00" required autofocus>
                </div>

                <div class="mb-4">
                    <label class="form-label"><?= $is_ar ? 'تفاصيل إضافية (اختياري)' : 'Additional Details' ?></label>
                    <textarea name="description" class="form-control" style="border-radius: 20px; border: 2px solid var(--border); padding: 20px; font-weight: 500;" rows="3" placeholder="<?= $is_ar ? 'أدخل ملاحظة تظهر في سجل الحسابات...' : 'Enter any notes for the ledger...' ?>"></textarea>
                </div>

                <button type="submit" class="btn-confirm">
                    <i class="fa fa-paper-plane me-2"></i> <?= $is_ar ? 'تنفيذ عملية السحب' : 'Confirm & Execute' ?>
                </button>
            </form>
        </div>

        <div class="text-center mt-5 text-muted small fw-bold">
            Top Accessories &bull; Profit Ledger Control &copy; 2025
        </div>
    </div>

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