<?php
session_start();
ob_start();  // Prevent header errors

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

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

$journal_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($journal_id <= 0) {
    echo "<p style='color:red;'>Invalid journal entry ID.</p>";
    include('../../includes/footer.php');
    ob_end_flush();
    exit();
}

// Fetch existing journal entry
$stmt = $conn->prepare("SELECT * FROM journal_entries WHERE id = ?");
$stmt->bind_param("i", $journal_id);
$stmt->execute();
$result = $stmt->get_result();
$entry = $result->fetch_assoc();
$stmt->close();

if (!$entry) {
    echo "<p style='color:red;'>Journal entry not found.</p>";
    include('../../includes/footer.php');
    ob_end_flush();
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entry_date = $_POST['entry_date'] ?? '';
    $description = trim($_POST['description'] ?? '');
    $store_id = intval($_POST['store_id'] ?? 0);
    $debit_account_id = intval($_POST['debit_account_id'] ?? 0);
    $credit_account_id = intval($_POST['credit_account_id'] ?? 0);
    $debit_amount = floatval($_POST['debit_amount'] ?? 0);
    $credit_amount = floatval($_POST['credit_amount'] ?? 0);
    $status = $_POST['status'] ?? 'posted';

    if ($entry_date && $debit_account_id && $credit_account_id && $debit_amount > 0 && $credit_amount > 0) {
        $stmtUpdate = $conn->prepare("
            UPDATE journal_entries
            SET entry_date = ?, description = ?, store_id = ?, 
                debit_account_id = ?, credit_account_id = ?, 
                debit_amount = ?, credit_amount = ?, status = ?
            WHERE id = ?
        ");
        $stmtUpdate->bind_param(
            "ssiiiddsi",
            $entry_date, $description, $store_id,
            $debit_account_id, $credit_account_id,
            $debit_amount, $credit_amount, $status, $journal_id
        );

        if ($stmtUpdate->execute()) {
            header("Location: journal_entry_view.php?id=" . $journal_id . "&msg=Updated+successfully");
            exit();
        } else {
            $error = "Update failed. Please try again.";
        }
        $stmtUpdate->close();
    } else {
        $error = "Please fill all required fields with valid amounts.";
    }
}

// Fetch supporting data
$stores = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL");
$accounts = $conn->query("SELECT id, account_name FROM accounts ORDER BY account_name");
?>

<style>
body {
    background: url('../../images/profile.jpg') center/cover fixed;
    font-family: 'Segoe UI', sans-serif;
    color: #eee;
}
.form-container {
    max-width: 900px;
    margin: 60px auto;
    background: rgba(255, 255, 255, 0.08);
    padding: 30px;
    border-radius: 15px;
}
h2 {
    color: #ffa500;
    margin-bottom: 20px;
}
.form-group {
    margin-bottom: 15px;
}
.form-group label {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
}
.form-group input, .form-group select, .form-group textarea {
    width: 100%;
    padding: 8px 10px;
    border-radius: 8px;
    border: none;
}
button {
    background: #ffa500;
    color: #222;
    border: none;
    padding: 10px 18px;
    border-radius: 8px;
    cursor: pointer;
}
button:hover {
    background: rgba(255,165,0,0.8);
}
.error {
    color: #f87171;
    margin-bottom: 10px;
}
a.cancel-link {
    margin-left: 20px;
    color: #ffa500;
    text-decoration: none;
}
a.cancel-link:hover {
    text-decoration: underline;
}
</style>

<div class="form-container">
    <h2>Edit Journal Entry</h2>

    <?php if (isset($error)): ?>
        <p class="error"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>

    <form method="POST">
        <div class="form-group">
            <label>Entry Date</label>
            <input type="date" name="entry_date" value="<?= htmlspecialchars($entry['entry_date']) ?>" required>
        </div>

        <div class="form-group">
            <label>Description</label>
            <textarea name="description"><?= htmlspecialchars($entry['description']) ?></textarea>
        </div>

        <div class="form-group">
            <label>Store</label>
            <select name="store_id">
                <option value="">-- Select Store --</option>
                <?php while ($s = $stores->fetch_assoc()): ?>
                    <option value="<?= $s['id'] ?>" <?= ($entry['store_id'] == $s['id'] ? 'selected' : '') ?>>
                        <?= htmlspecialchars($s['store_name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Debit Account</label>
            <select name="debit_account_id" required>
                <option value="">-- Select Debit Account --</option>
                <?php foreach ($accounts as $a): ?>
                    <option value="<?= $a['id'] ?>" <?= ($entry['debit_account_id'] == $a['id'] ? 'selected' : '') ?>>
                        <?= htmlspecialchars($a['account_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Debit Amount</label>
            <input type="number" step="0.01" name="debit_amount" value="<?= htmlspecialchars($entry['debit_amount']) ?>" required>
        </div>

        <div class="form-group">
            <label>Credit Account</label>
            <select name="credit_account_id" required>
                <option value="">-- Select Credit Account --</option>
                <?php foreach ($accounts as $a): ?>
                    <option value="<?= $a['id'] ?>" <?= ($entry['credit_account_id'] == $a['id'] ? 'selected' : '') ?>>
                        <?= htmlspecialchars($a['account_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Credit Amount</label>
            <input type="number" step="0.01" name="credit_amount" value="<?= htmlspecialchars($entry['credit_amount']) ?>" required>
        </div>

        <div class="form-group">
            <label>Status</label>
            <select name="status">
                <option value="posted" <?= $entry['status'] == 'posted' ? 'selected' : '' ?>>Posted</option>
                <option value="pending" <?= $entry['status'] == 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="voided" <?= $entry['status'] == 'voided' ? 'selected' : '' ?>>Voided</option>
            </select>
        </div>

        <button type="submit">Update Journal Entry</button>
        <a href="journal_entry_view.php?id=<?= $journal_id ?>" class="cancel-link">Cancel</a>
    </form>
</div>

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