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

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

$journal_entry_id = intval($_GET['id'] ?? 0);
$current_user_id = $_SESSION['user_id'];

if ($journal_entry_id <= 0) {
    die("Invalid journal entry ID.");
}

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

if (!$journal) {
    die("Journal entry not found.");
}

if ($journal['status'] === 'posted') {
    die("Journal entry already posted.");
}

// Fetch journal entry lines
$stmtLines = $conn->prepare("SELECT * FROM journal_lines WHERE je_id = ?");
$stmtLines->bind_param('i', $journal_entry_id);
$stmtLines->execute();
$res = $stmtLines->get_result();
$lines = $res->fetch_all(MYSQLI_ASSOC);
$stmtLines->close();

if (empty($lines)) {
    die("No journal lines found to post.");
}

// Post each line into financial_transactions
foreach ($lines as $line) {
    $account_id = (int)$line['account_id'];
    $debit = floatval($line['debit']);
    $credit = floatval($line['credit']);
    $line_desc = trim($line['description'] ?? '');

    $debit_value = $debit > 0 ? $debit : 0;
    $credit_value = $credit > 0 ? $credit : 0;
    $amount = max($debit_value, $credit_value);
    $store_id = (int)$journal['store_id'];

    // Fetch account name
    $account_name = '';
    $stmtAcc = $conn->prepare("SELECT account_name FROM accounts WHERE id = ?");
    $stmtAcc->bind_param('i', $account_id);
    $stmtAcc->execute();
    $stmtAcc->bind_result($account_name);
    $stmtAcc->fetch();
    $stmtAcc->close();

    if (empty($account_name)) {
        $account_name = 'Unknown Account';
    }

    // Use line description or journal description
    $description = !empty($line_desc) ? $line_desc : $journal['description'];

    // Prepare INSERT for financial_transactions
    $stmtFT = $conn->prepare("
        INSERT INTO financial_transactions
        (transaction_date, account_id, type, amount, payment_method, account, description, reference_id, store_id, created_by, status, created_at, debit, credit, linked_journal_entry_id)
        VALUES (?, ?, 'journal', ?, 'journal', ?, ?, ?, ?, ?, 'posted', NOW(), ?, ?, ?)
    ");

    if (!$stmtFT) {
        die("Prepare failed: " . $conn->error);
    }

    // Correct binding: 13 variables = 'sidsssiiddi'
    $stmtFT->bind_param(
        'sidsssiiddi',
        $journal['entry_date'],    // s - transaction_date
        $account_id,               // i - account_id
        $amount,                   // d - amount
        $account_name,             // s - account
        $description,              // s - description
        $journal_entry_id,         // i - reference_id
        $store_id,                 // s (string because of mismatch; could be i if store_id is strictly integer)
        $current_user_id,          // i - created_by
        $debit_value,              // d - debit
        $credit_value,             // d - credit
        $journal_entry_id          // i - linked_journal_entry_id
    );

    if (!$stmtFT->execute()) {
        die("Error posting financial transaction: " . $stmtFT->error);
    }

    $stmtFT->close();
}

// Update journal entry status to 'posted'
$stmtUpdate = $conn->prepare("UPDATE journal_entries SET status = 'posted' WHERE id = ?");
$stmtUpdate->bind_param('i', $journal_entry_id);
$stmtUpdate->execute();
$stmtUpdate->close();

echo "Journal entry posted successfully.";
?>
