<?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');

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $entry_date = $_POST['entry_date'] ?? date('Y-m-d');
    $description = trim($_POST['description'] ?? '');
    $store_id = intval($_POST['store_id'] ?? 0);
    $status = $_POST['status'] ?? 'draft';
    $created_by = $_SESSION['user_id'];

    $accounts = $_POST['account_id'] ?? [];
    $debits = $_POST['debit_amount'] ?? [];
    $credits = $_POST['credit_amount'] ?? [];
    $line_descriptions = $_POST['line_description'] ?? [];

    $total_debit = 0;
    $total_credit = 0;

    // Validate inputs
    foreach ($accounts as $key => $account_id) {
        $account_id = intval($account_id);
        $debit = floatval($debits[$key]);
        $credit = floatval($credits[$key]);

        if ($account_id <= 0 || ($debit <= 0 && $credit <= 0)) {
            $errors[] = "All lines must have a valid account and either debit or credit.";
        }

        if ($debit > 0 && $credit > 0) {
            $errors[] = "A single line cannot have both debit and credit amounts.";
        }

        $total_debit += $debit;
        $total_credit += $credit;
    }

    if (!$entry_date || !$description || !$store_id) {
        $errors[] = "Entry date, description, and store are required.";
    }

    if (empty($accounts)) {
        $errors[] = "At least one journal line is required.";
    }

    if (round($total_debit, 2) !== round($total_credit, 2)) {
        $errors[] = "Total debits must equal total credits.";
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("
            INSERT INTO journal_entries (entry_date, description, store_id, status, created_by, created_at)
            VALUES (?, ?, ?, ?, ?, NOW())
        ");
        $stmt->bind_param('sssis', $entry_date, $description, $store_id, $status, $created_by);

        if ($stmt->execute()) {
            $journal_entry_id = $stmt->insert_id;
            $stmt->close();

            foreach ($accounts as $key => $account_id) {
                $account_id = intval($account_id);
                $debit = floatval($debits[$key]);
                $credit = floatval($credits[$key]);
                $line_desc = trim($line_descriptions[$key]);

                if ($account_id > 0 && ($debit > 0 || $credit > 0)) {
                    $stmtLine = $conn->prepare("
                        INSERT INTO journal_lines 
                        (je_id, account_id, debit, credit, description, created_at)
                        VALUES (?, ?, ?, ?, ?, NOW())
                    ");
                    $stmtLine->bind_param('iidds', $journal_entry_id, $account_id, $debit, $credit, $line_desc);
                    $stmtLine->execute();
                    $stmtLine->close();
                }
            }

            $success = "Journal entry with multiple lines recorded successfully.";
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
    }
}

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

<style>
body {
    background: url('../../images/profile.jpg') center/cover fixed;
    font-family: 'Segoe UI', sans-serif;
    color: #eee;
    margin: 0;
}
.wrap {
    max-width: 900px;
    margin: 40px auto;
    background: rgba(255,255,255,0.1);
    padding: 30px;
    border-radius: 15px;
}
h2 {
    color: #ffa500;
    margin-bottom: 20px;
}
input, select, textarea, button {
    padding: 10px;
    margin-top: 10px;
    border-radius: 8px;
    border: none;
}
button {
    background: #ffa500;
    color: #222;
    cursor: pointer;
    font-weight: bold;
}
.error, .success {
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 8px;
}
.error {
    background: rgba(220, 38, 38, 0.2);
}
.success {
    background: rgba(16, 185, 129, 0.2);
}
.line-row {
    display: flex;
    gap: 10px;
    margin-top: 10px;
}
.line-row select, .line-row input {
    flex: 1;
}
.line-row button {
    background: red;
    color: #fff;
}
</style>

<div class="wrap">
    <h2>New Journal Entry (Multiple Lines)</h2>

    <?php if ($errors): ?>
        <div class="error"><?= implode('<br>', $errors) ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="success"><?= $success ?></div>
    <?php endif; ?>

    <form method="POST">
        <label>Entry Date</label>
        <input type="date" name="entry_date" value="<?= htmlspecialchars($_POST['entry_date'] ?? date('Y-m-d')) ?>">

        <label>Description</label>
        <textarea name="description"><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>

        <label>Store</label>
        <select name="store_id">
            <option value="">-- Select Store --</option>
            <?php while ($store = $stores->fetch_assoc()): ?>
                <option value="<?= $store['id'] ?>" <?= (isset($_POST['store_id']) && $_POST['store_id'] == $store['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($store['store_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <label>Journal Lines</label>
        <div id="journal-lines">
            <div class="line-row">
                <select name="account_id[]">
                    <option value="">-- Account --</option>
                    <?php while ($acc = $accounts_list->fetch_assoc()): ?>
                        <option value="<?= $acc['id'] ?>"><?= htmlspecialchars($acc['account_name']) ?></option>
                    <?php endwhile; ?>
                </select>
                <input type="number" step="0.01" name="debit_amount[]" placeholder="Debit">
                <input type="number" step="0.01" name="credit_amount[]" placeholder="Credit">
                <input type="text" name="line_description[]" placeholder="Line description">
                <button type="button" onclick="removeLine(this)">X</button>
            </div>
        </div>
        <button type="button" onclick="addLine()">+ Add Line</button>

        <label>Status</label>
        <select name="status">
            <option value="draft" <?= (($_POST['status'] ?? '') == 'draft') ? 'selected' : '' ?>>Draft</option>
            <option value="posted" <?= (($_POST['status'] ?? '') == 'posted') ? 'selected' : '' ?>>Posted</option>
        </select>

        <button type="submit">Save Entry</button>
    </form>
</div>

<script>
function addLine() {
    const container = document.getElementById('journal-lines');
    const newLine = container.firstElementChild.cloneNode(true);
    newLine.querySelectorAll('input').forEach(input => input.value = '');
    container.appendChild(newLine);
}

function removeLine(btn) {
    const container = document.getElementById('journal-lines');
    if (container.children.length > 1) {
        btn.parentElement.remove();
    }
}
</script>

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