<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// إعدادات اللغة والاتجاه
$lang = $_SESSION['lang'] ?? 'ar';
$dir = ($lang === 'ar') ? 'rtl' : 'ltr';

if (!isset($_GET['id'])) {
    header('Location: index.php');
    exit;
}

$id = intval($_GET['id']);

// تحديث المصروف
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $expense_type = $_POST['expense_type'];
    $amount = $_POST['amount'];
    $description = $_POST['description'];
    $expense_date = $_POST['expense_date'];
    $branch_name = $_POST['branch_name'];
    $paid_to = $_POST['paid_to'];

    $stmt = $conn->prepare("UPDATE expenses SET expense_type = ?, amount = ?, description = ?, expense_date = ?, branch_name = ?, paid_to = ? WHERE id = ?");
    $stmt->execute([$expense_type, $amount, $description, $expense_date, $branch_name, $paid_to, $id]);

    // 💡 التعديل هنا: إعادة التوجيه مع متغير النجاح
    header("Location: edit.php?id={$id}&success=1"); 
    exit;
}

// جلب بيانات المصروف
$stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ?");
$stmt->execute([$id]);
$expense = $stmt->fetch();

if (!$expense) {
    echo $lang === 'ar' ? "المصروف غير موجود" : "Gider bulunamadı";
    exit;
}

// جلب أسماء الفروع المتاحة
try {
    $stmt_branches = $conn->query("SELECT DISTINCT branch_name FROM branches ORDER BY branch_name ASC");
    $db_branches = $stmt_branches->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    $db_branches = $conn->query("SELECT DISTINCT branch_name FROM expenses WHERE branch_name IS NOT NULL AND branch_name != ''")->fetchAll(PDO::FETCH_COLUMN);
}

?>

<?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" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;800&display=swap" rel="stylesheet">

<style>
/* إبقاء خط Cairo */
body {
    font-family: 'Cairo', sans-serif;
}
</style>

<?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 sm:px-6 lg:px-8">
        
        <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-6 flex items-center border-b pb-3 border-indigo-400/50">
                <i class="fas fa-edit text-indigo-500 <?= $dir === 'rtl' ? 'ml-3' : 'mr-3' ?>"></i> 
                <?= __('edit_expense_title') ?>
            </h2>
            
            <?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
                <div class="bg-green-100 dark:bg-green-900 border border-green-400 text-green-700 dark:text-green-300 px-4 py-3 rounded-lg mb-6 shadow-md transition duration-300 transform animate-pulse" role="alert">
                    <strong class="font-bold <?= $dir === 'rtl' ? 'ml-2' : 'mr-2' ?>"><i class="fas fa-check-circle mr-1"></i> <?= __('success_save_title') ?></strong>
                    <span class="block sm:inline"><?= __('success_save_msg') ?></span>
                </div>
            <?php endif; ?>

            <form method="POST" class="space-y-6">

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="paid_to" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('paid_to_label') ?></label>
                        <input type="text" id="paid_to" name="paid_to" value="<?= htmlspecialchars($expense['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:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-sm">
                    </div>

                    <div>
                        <label for="expense_type" 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" id="expense_type" name="expense_type" value="<?= htmlspecialchars($expense['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:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-sm">
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('amount_label') ?> (<?= __('currency_name') ?>) <span class="text-red-500">*</span></label>
                        <input type="number" id="amount" name="amount" step="0.01" value="<?= htmlspecialchars($expense['amount'] ?? 0) ?>" 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:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-sm">
                    </div>

                    <div>
                        <label for="expense_date" 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" id="expense_date" name="expense_date" value="<?= htmlspecialchars($expense['expense_date'] ?? date('Y-m-d')) ?>" 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:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-sm">
                    </div>
                </div>

                <div>
                    <label for="branch_name" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('branch_label') ?></label>
                    <select id="branch_name" name="branch_name" 
                            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:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-sm text-sm">
                        <option value=""><?= __('select_branch') ?></option>
                        <?php foreach ($db_branches as $b): ?>
                            <option value="<?= htmlspecialchars($b) ?>" <?= ($expense['branch_name'] === $b) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($b) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"><?= __('description_label') ?></label>
                    <textarea id="description" name="description" rows="3" 
                              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:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-sm"><?= htmlspecialchars($expense['description'] ?? '') ?></textarea>
                </div>

                <div class="flex flex-col sm:flex-row justify-between gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                    
                    <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 transform hover:scale-[1.01]">
                        <i class="fas <?= $dir === 'rtl' ? 'fa-arrow-right ml-2' : 'fa-arrow-left mr-2' ?>"></i> <?= __('back_to_report') ?>
                    </a>
                    
                    <button type="submit"
                        class="sm:w-1/2 w-full bg-indigo-600 text-white font-bold py-3 rounded-xl hover:bg-indigo-700 transition shadow-lg transform hover:scale-[1.01] order-1 sm:order-2">
                        <i class="fas fa-save <?= $dir === 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('save_changes') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include('../includes/footer.php'); ?>