<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/sidebar.php');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid transaction ID.");
}

$transaction_id = (int)$_GET['id'];
$error = $success = '';

// Fetch existing transaction data
$stmt = $conn->prepare("SELECT transaction_date, type, amount, payment_method, account, description, store_id FROM financial_transactions WHERE id = ? AND status != 'voided' LIMIT 1");
$stmt->bind_param('i', $transaction_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Transaction not found or has been voided.");
}

$transaction = $result->fetch_assoc();
$stmt->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $transaction_date = $_POST['transaction_date'];
    $type = $_POST['type'];
    $amount = floatval($_POST['amount']);
    $payment_method = $_POST['payment_method'];
    $account = $_POST['account'];
    $description = $_POST['description'];
    $store_id = $_POST['store_id'];
    $updated_by = $_SESSION['user_id'];

    $stmt_update = $conn->prepare("UPDATE financial_transactions SET transaction_date = ?, type = ?, amount = ?, payment_method = ?, account = ?, description = ?, store_id = ?, updated_by = ?, updated_at = NOW() WHERE id = ?");
    $stmt_update->bind_param('ssdsssiii', $transaction_date, $type, $amount, $payment_method, $account, $description, $store_id, $updated_by, $transaction_id);

    if ($stmt_update->execute()) {
        $success = "✅ Transaction updated successfully.";
        // Refresh the $transaction array with new values
        $transaction = [
            'transaction_date' => $transaction_date,
            'type' => $type,
            'amount' => $amount,
            'payment_method' => $payment_method,
            'account' => $account,
            'description' => $description,
            'store_id' => $store_id,
        ];
    } else {
        $error = "❌ Failed to update transaction.";
    }
    $stmt_update->close();
}
?>

<style>
    /* Same styles as add_transaction.php */
    body {
        background: #1e1e2f url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        margin: 0;
        color: #eee;
    }
    .overlay {
        position: fixed;
        top: 0; left: 220px;
        width: calc(100% - 220px);
        height: 100%;
        background: rgba(30, 30, 47, 0.8);
        z-index: -1;
    }
    .content {
        margin-left: 220px;
        padding: 40px 50px 50px 50px;
        max-width: 900px;
        min-height: 100vh;
        box-sizing: border-box;
    }
    .card {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 18px;
        padding: 40px 50px;
        box-shadow: 0 12px 36px rgba(255, 165, 0, 0.3);
        backdrop-filter: blur(16px);
        border: 1px solid rgba(255, 165, 0, 0.4);
        color: #fff;
        box-sizing: border-box;
    }
    h1.page-title {
        font-size: 28px;
        font-weight: 700;
        margin-bottom: 30px;
        color: #ffa500;
        text-shadow: 0 0 10px #ffa500;
    }
    h2.card-title {
        font-size: 22px;
        margin-bottom: 25px;
        font-weight: 600;
        border-bottom: 2px solid rgba(255, 165, 0, 0.5);
        padding-bottom: 12px;
        color: #ffa500;
        text-shadow: 0 0 6px #ffa500;
    }
    .form-group {
        margin-bottom: 24px;
    }
    label {
        display: block;
        font-weight: 600;
        color: #ffa500;
        margin-bottom: 8px;
        letter-spacing: 0.04em;
        user-select: none;
        text-shadow: 0 0 3px rgba(255, 165, 0, 0.7);
    }
    input[type="text"],
    input[type="date"],
    input[type="number"],
    select,
    textarea {
        width: 100%;
        padding: 14px 18px;
        border-radius: 12px;
        border: none;
        outline: none;
        background: rgba(255, 255, 255, 0.9);
        color: #222;
        font-weight: 600;
        font-size: 16px;
        box-shadow: inset 0 3px 8px rgba(0,0,0,0.1);
        transition: box-shadow 0.3s ease;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        user-select: text;
    }
    input[type="text"]:focus,
    input[type="date"]:focus,
    input[type="number"]:focus,
    select:focus,
    textarea:focus {
        box-shadow: 0 0 12px #ffa500;
        background: #fff;
    }
    textarea {
        resize: vertical;
        min-height: 90px;
    }
    .btn-submit {
        width: 100%;
        background: #ffa500;
        color: #222;
        font-weight: 700;
        font-size: 18px;
        padding: 14px;
        border: none;
        border-radius: 14px;
        cursor: pointer;
        box-shadow: 0 4px 14px rgba(255, 165, 0, 0.7);
        transition: background-color 0.3s ease, color 0.3s ease;
        user-select: none;
        letter-spacing: 0.05em;
    }
    .btn-submit:hover,
    .btn-submit:focus {
        background: #e59400;
        color: #111;
        box-shadow: 0 6px 20px rgba(230, 140, 0, 0.9);
    }
    .alert-success, .alert-error {
        padding: 16px 20px;
        border-radius: 12px;
        margin-bottom: 28px;
        font-weight: 700;
        font-size: 16px;
        letter-spacing: 0.05em;
        box-shadow: 0 4px 14px rgba(0,0,0,0.15);
        user-select: none;
    }
    .alert-success {
        background: rgba(16,185,129,0.18);
        border-left: 7px solid #10b981;
        color: #10b981;
        text-shadow: 0 0 6px #10b981;
    }
    .alert-error {
        background: rgba(239,68,68,0.18);
        border-left: 7px solid #ef4444;
        color: #ef4444;
        text-shadow: 0 0 6px #ef4444;
    }
    @media (max-width: 950px) {
        .content {
            margin-left: 0;
            padding: 30px 20px 50px 20px;
        }
        .overlay {
            left: 0;
            width: 100%;
        }
    }
</style>

<div class="overlay"></div>

<div class="content" role="main" aria-label="Edit Financial Transaction">
    <h1 class="page-title">✏️ Edit Transaction #<?= htmlspecialchars($transaction_id) ?></h1>

    <?php if ($success): ?>
        <div class="alert-success" role="alert" aria-live="polite"><?= $success ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert-error" role="alert" aria-live="assertive"><?= $error ?></div>
    <?php endif; ?>

    <div class="card" role="form" aria-labelledby="form-title">
        <h2 id="form-title" class="card-title">Edit Transaction Details</h2>

        <form method="POST" novalidate>
            <div class="form-group">
                <label for="transaction_date">Transaction Date</label>
                <input id="transaction_date" type="date" name="transaction_date" required aria-required="true"
                    value="<?= htmlspecialchars($transaction['transaction_date']) ?>" />
            </div>

            <div class="form-group">
                <label for="type">Transaction Type</label>
                <select id="type" name="type" required aria-required="true" >
                    <option value="">-- Select Type --</option>
                    <?php
                    $types = ['deposit', 'withdrawal', 'expense', 'cogs', 'loan', 'repayment', 'sale_income', 'supplier_payment', 'transfer'];
                    foreach ($types as $t) {
                        $selected = ($transaction['type'] === $t) ? "selected" : "";
                        echo '<option value="' . $t . '" ' . $selected . '>' . ucfirst(str_replace('_', ' ', $t)) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <div class="form-group">
                <label for="payment_method">Payment Method</label>
                <select id="payment_method" name="payment_method" required aria-required="true">
                    <option value="">-- Select Method --</option>
                    <?php
                    $methods = ['cash', 'bank_transfer', 'cheque', 'mobile_money', 'other'];
                    foreach ($methods as $method) {
                        $selected = ($transaction['payment_method'] === $method) ? "selected" : "";
                        echo '<option value="' . $method . '" ' . $selected . '>' . ucfirst(str_replace('_', ' ', $method)) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <div class="form-group">
                <label for="account">Account</label>
                <input id="account" type="text" name="account" required aria-required="true" autocomplete="off"
                    value="<?= htmlspecialchars($transaction['account']) ?>" />
            </div>

            <div class="form-group">
                <label for="amount">Amount (MWK)</label>
                <input id="amount" type="number" step="0.01" name="amount" required aria-required="true" min="0.01"
                    value="<?= htmlspecialchars($transaction['amount']) ?>" />
            </div>

            <div class="form-group">
                <label for="store_id">Store</label>
                <select id="store_id" name="store_id" required aria-required="true">
                    <option value="">-- Select Store --</option>
                    <?php
                    $stores = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL ORDER BY store_name ASC");
                    while ($row = $stores->fetch_assoc()) {
                        $selected = ($transaction['store_id'] == $row['id']) ? "selected" : "";
                        echo '<option value="' . htmlspecialchars($row['id']) . '" ' . $selected . '>' . htmlspecialchars($row['store_name']) . '</option>';
                    }
                    ?>
                </select>
            </div>

            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description" rows="4" autocomplete="off"><?= htmlspecialchars($transaction['description']) ?></textarea>
            </div>

            <button type="submit" class="btn-submit" aria-label="Update transaction">💾 Update Transaction</button>
        </form>
    </div>
</div>

<?php include('../../includes/footer.php'); ?>
