<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// 1. احذف تعريف الدالة function __() من هنا تماماً لأنها موجودة في header.php

/**
 * خريطة الفروع: تبقى كما هي
 */
$branches_map = [
    'فرع عمان'   => 'branch_amman',
    'فرع إربد'   => 'branch_irbid',
    'فرع الزرقاء' => 'branch_zarqa'
];

$lang = $_SESSION['lang'] ?? 'ar';
$dir = ($lang === 'ar') ? 'rtl' : 'ltr';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $expense_type = trim($_POST['expense_type'] ?? '');
    $amount       = floatval($_POST['amount'] ?? 0);
    $paid_to      = trim($_POST['paid_to'] ?? null);
    $branch_name  = trim($_POST['branch_name'] ?? ''); // سيستلم القيمة العربية من الـ select
    $expense_date = $_POST['expense_date'] ?? date('Y-m-d');
    $description  = trim($_POST['description'] ?? '');

    if ($expense_type == '' || $amount <= 0 || $branch_name == '') {
        $error = __('validation_error_msg');
    } else {
        try {
            $stmt = $conn->prepare("
                INSERT INTO expenses (expense_type, amount, expense_date, description, paid_to, branch_name)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            // التخزين يتم باللغة العربية لتوحيد التقارير
            $stmt->execute([$expense_type, $amount, $expense_date, $description, $paid_to, $branch_name]);
            
            header('Location: add.php?success=1');
            exit;
        } catch (PDOException $e) {
            $error = __('db_error_msg') . ": " . $e->getMessage();
        }
    }
}

$old_data = [
    'paid_to'      => $_POST['paid_to'] ?? '',
    'branch_name'  => $_POST['branch_name'] ?? '',
    'expense_type' => $_POST['expense_type'] ?? '',
    'amount'       => $_POST['amount'] ?? '',
    'expense_date' => $_POST['expense_date'] ?? date('Y-m-d'),
    'description'  => $_POST['description'] ?? '',
];
?>

<?php include('../includes/header.php'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;800&display=swap" rel="stylesheet">
<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen bg-gray-50 dark:bg-gray-900 pb-16 font-[Cairo]" dir="<?= $dir ?>">
    <div class="max-w-3xl mx-auto py-10 px-4">
        
        <div class="bg-white dark:bg-gray-800 shadow-2xl rounded-xl p-8 border-t-8 border-indigo-600">
            <h2 class="text-3xl font-extrabold text-gray-800 dark:text-gray-100 mb-8 text-center flex items-center justify-center">
                <i class="fas fa-money-bill-transfer text-indigo-500 <?= $dir === 'rtl' ? 'ml-3' : 'mr-3' ?>"></i> 
                <?= __('add_new_expense') ?>
            </h2>

            <?php if (isset($error)): ?>
                <div class="bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg mb-6 shadow-md border border-red-400">
                    <strong class="font-bold"><?= __('error_title') ?></strong>
                    <span class="block sm:inline"><?= htmlspecialchars($error) ?></span>
                </div>
            <?php elseif (isset($_GET['success'])): ?>
                <div class="bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 px-4 py-3 rounded-lg mb-6 shadow-md border border-green-400">
                    <strong class="font-bold"><?= __('success_title') ?></strong>
                    <span class="block sm:inline"><?= __('add_success_msg') ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" class="space-y-6" autocomplete="off">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('paid_to_label') ?></label>
                        <input type="text" name="paid_to" value="<?= htmlspecialchars($old_data['paid_to']) ?>"
                            class="w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-4 py-2.5 focus:ring-4 focus:ring-indigo-500/50 outline-none transition shadow-sm"
                            placeholder="<?= __('paid_to_placeholder') ?>" />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('branch_label') ?> <span class="text-red-500">*</span></label>
                        <select name="branch_name" required
                            class="w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-4 py-2.5 focus:ring-4 focus:ring-indigo-500/50 outline-none transition shadow-sm text-sm">
                            <option value=""><?= __('select_branch') ?></option>
                            <?php foreach ($branches_map as $arabic_val => $lang_key): ?>
                                <option value="<?= htmlspecialchars($arabic_val) ?>" <?= ($old_data['branch_name'] === $arabic_val) ? 'selected' : '' ?>>
                                    <?= __($lang_key) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('expense_type_label') ?> <span class="text-red-500">*</span></label>
                        <input type="text" name="expense_type" value="<?= htmlspecialchars($old_data['expense_type']) ?>" required
                            class="w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-4 py-2.5 focus:ring-4 focus:ring-indigo-500/50 outline-none transition shadow-sm"
                            placeholder="<?= __('expense_type_placeholder') ?>" />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('amount_label') ?> <span class="text-red-500">*</span></label>
                        <input type="number" name="amount" step="0.01" min="0.01" value="<?= htmlspecialchars($old_data['amount']) ?>" required
                            class="w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-4 py-2.5 focus:ring-4 focus:ring-indigo-500/50 outline-none transition shadow-sm"
                            placeholder="<?= __('amount_placeholder') ?>" />
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('expense_date_label') ?> <span class="text-red-500">*</span></label>
                    <input type="date" name="expense_date" value="<?= htmlspecialchars($old_data['expense_date']) ?>" required
                        class="w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-4 py-2.5 focus:ring-4 focus:ring-indigo-500/50 outline-none transition shadow-sm" />
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('description_label') ?></label>
                    <textarea name="description" rows="4"
                        class="w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-4 py-2.5 focus:ring-4 focus:ring-indigo-500/50 outline-none transition shadow-sm"
                        placeholder="<?= __('description_placeholder') ?>"><?= htmlspecialchars($old_data['description']) ?></textarea>
                </div>

                <div class="flex flex-col sm:flex-row justify-between gap-4 pt-4">
                    <?php if ($_SESSION['user']['role'] === 'admin'): ?>
                    <a href="report.php" class="sm:w-1/2 w-full text-center bg-gray-300 text-gray-800 font-semibold py-3 rounded-xl hover:bg-gray-400 transition shadow-md flex items-center justify-center order-2 sm:order-1">
                        <i class="fas <?= $dir === 'rtl' ? 'fa-arrow-right ml-2' : 'fa-arrow-left mr-2' ?>"></i> <?= __('back_to_report') ?>
                    </a>
                    <?php endif; ?>

                    <button type="submit" class="<?= ($_SESSION['user']['role'] === 'admin') ? 'sm:w-1/2' : 'w-full' ?> bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 rounded-xl shadow-lg transition duration-300 transform hover:scale-[1.01] order-1 sm:order-2">
                        <i class="fas fa-plus-circle <?= $dir === 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('save_expense_btn') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php include('../includes/footer.php'); ?>