<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

ob_start(); 
include "db.php";

// ==========================================
// 1. INLINE DYNAMIC REFERENCE LOAD (AJAX)
// ==========================================
if (isset($_GET['action']) && $_GET['action'] === 'get_reference' && isset($_GET['type'])) {
    $type = $_GET['type'];
    $options = "<option value=''>-- Select Reference Name --</option>";

    if ($type == 'customer') {
        $query = "SELECT id, name FROM customers ORDER BY name ASC";
        $result = $conn->query($query);
        while ($row = $result->fetch_assoc()) {
            $options .= "<option value='" . $row['id'] . "'>" . htmlspecialchars($row['name']) . "</option>";
        }
    } elseif ($type == 'supplier') {
        $query = "SELECT id, name FROM suppliers ORDER BY name ASC";
        $result = $conn->query($query);
        while ($row = $result->fetch_assoc()) {
            $options .= "<option value='" . $row['id'] . "'>" . htmlspecialchars($row['name']) . "</option>";
        }
    } else {
        $stmt = $conn->prepare("SELECT account_name FROM chart_of_accounts WHERE UPPER(main_type) = ? OR UPPER(sub_type) = ? ORDER BY account_name ASC");
        $upper_type = strtoupper($type);
        $stmt->bind_param("ss", $upper_type, $upper_type);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $options .= "<option value='" . htmlspecialchars($row['account_name']) . "'>" . htmlspecialchars($row['account_name']) . "</option>";
        }
        $stmt->close();
    }
    
    echo $options;
    exit; 
}

// ==========================================
// 2. TRANSACTION SUBMISSION HANDLING
// ==========================================
$sidebar_path = "/home/tameeralmadina/public_html/TAM/sidebar";

if (isset($_POST['submit'])) {
    $date            = $_POST['date'];
    $form_type      = $_POST['type']; 
    $amount         = floatval($_POST['amount']);
    $posted_amt_type = isset($_POST['amount_type']) ? $_POST['amount_type'] : '';    
    $reference_type = $_POST['reference_type']; 
    $reference_id   = isset($_POST['reference_id']) ? trim($_POST['reference_id']) : '';   
    $description    = trim($_POST['description']);

    $db_type = ($form_type === 'Received') ? 'DEBIT' : 'CREDIT';

    $db_amount_type = 'CASH'; 
    if (!empty($posted_amt_type) && strpos(strtoupper($posted_amt_type), 'CASH') === false) {
        $db_amount_type = 'BANK';
    }

    $db_ref_type = 'GENERAL';
    $upper_ref_type = strtoupper($reference_type);
    if (in_array($upper_ref_type, ['CUSTOMER', 'SUPPLIER', 'EXPENSE'])) {
        $db_ref_type = $upper_ref_type;
    }

    $ref_name_string = "";
    $final_ref_id = null; 

    if (is_numeric($reference_id)) {
        $final_ref_id = intval($reference_id);
    } else {
        $ref_name_string = $reference_id; 
        if(!empty($ref_name_string)) {
            $description = "[Account: " . $ref_name_string . "] " . $description;
        }
    }

    $stmt = $conn->prepare("
        INSERT INTO transactions 
        (date, type, amount, amount_type, reference_id, reference_type, description) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->bind_param(
        "ssssiss", 
        $date, 
        $db_type, 
        $amount, 
        $db_amount_type, 
        $final_ref_id, 
        $db_ref_type, 
        $description
    );

    if ($stmt->execute()) {
        $stmt->close();

        // Step A: Payment Source Ledger Update
        if (!empty($posted_amt_type)) {
            if ($form_type == 'Received') {
                $update_source = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance + ? WHERE account_name = ?");
            } else {
                $update_source = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance - ? WHERE account_name = ?");
            }
            if ($update_source) {
                $update_source->bind_param("ds", $amount, $posted_amt_type);
                $update_source->execute();
                $update_source->close();
            }
        }

        // Step B: Target Reference Head Update
        if (!empty($ref_name_string)) {
            if ($form_type == 'Paid') {
                $update_head = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance + ? WHERE account_name = ?");
            } else {
                $update_head = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance - ? WHERE account_name = ?");
            }
            if ($update_head) {
                $update_head->bind_param("ds", $amount, $ref_name_string);
                $update_head->execute();
                $update_head->close();
            }
        } 
        elseif ($final_ref_id > 0) {
            $coa_target_head = ($reference_type == 'customer') ? 'Product Sales' : 'SUPPLIER';
            
            if ($reference_type == 'customer') {
                if ($form_type == 'Received') {
                    $update_party = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance - ? WHERE sub_type = ? OR account_name = ?");
                } else {
                    $update_party = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance + ? WHERE sub_type = ? OR account_name = ?");
                }
            } 
            elseif ($reference_type == 'supplier') {
                if ($form_type == 'Paid') {
                    $update_party = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance - ? WHERE sub_type = ? OR account_name = ?");
                } else {
                    $update_party = $conn->prepare("UPDATE chart_of_accounts SET current_balance = current_balance + ? WHERE sub_type = ? OR account_name = ?");
                }
            }

            if (isset($update_party) && $update_party) {
                $update_party->bind_param("dss", $amount, $coa_target_head, $coa_target_head);
                $update_party->execute();
                $update_party->close();
            }
        }

        ob_end_clean();
        header("Location: transactions_view.php");
        exit;
    } else {
        $error = "Database Error: " . $stmt->error;
    }
}

// Fetch Accounts from DB for Dropdown
$accounts_query = "SELECT account_name, main_type, sub_type FROM chart_of_accounts WHERE UPPER(main_type) IN ('ASSET', 'CASH', 'BANK') OR UPPER(sub_type) LIKE '%CASH%' OR UPPER(sub_type) LIKE '%BANK%' ORDER BY account_name ASC";
$accounts_result = $conn->query($accounts_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Transaction - Tameer Al Madina</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { background: #F4F6F9; font-family: 'Poppins', sans-serif; min-height: 100vh; }
.main-layout { display: flex; width: 100%; min-height: 100vh; position: relative; }
aside, .sidebar, [class*="sidebar"] { width: 260px; min-width: 260px; height: 100vh; position: fixed; top: 0; left: 0; z-index: 1000; transition: all 0.3s ease; }
.content-wrapper { flex: 1; margin-left: 260px; display: flex; flex-direction: column; background: #F4F6F9; min-width: 0; width: calc(100% - 260px); transition: all 0.3s ease; }
.top-navbar { height: 60px; background: #FFFFFF; display: flex; justify-content: space-between; align-items: center; padding: 0 30px; border-bottom: 1px solid #EAEAEA; }
.navbar-left-flex { display: flex; align-items: center; gap: 15px; }
.mobile-menu-toggle { display: none; font-size: 20px; color: #0A192F; cursor: pointer; background: #F4F6F9; width: 38px; height: 38px; align-items: center; justify-content: center; border-radius: 6px; border: 1px solid #E2E8F0; }
.search-container { position: relative; width: 300px; }
.search-container input { width: 100%; padding: 8px 15px 8px 40px; background: #F8F9FA; border: 1px solid #E2E8F0; border-radius: 8px; font-size: 13px; outline: none; }
.search-container i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #A0AEC0; }
.user-profile { display: flex; align-items: center; gap: 20px; }
.profile-info { display: flex; align-items: center; gap: 10px; }
.profile-info i.profile-icon { font-size: 26px; color: #4A5568; background: #F4F6F9; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 1px solid #E2E8F0; }
.profile-text h4 { font-size: 13px; color: #1A202C; font-weight: 600; }
.profile-text p { font-size: 11px; color: #718096; }
.page-container { padding: 20px 30px; flex: 1; display: flex; flex-direction: column; }
.form-card { background: #FFFFFF; border-radius: 12px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05); overflow: hidden; width: 100%; display: flex; flex-direction: column; flex: 1; }
form { display: flex; flex-direction: column; flex: 1; }
.form-banner { background: linear-gradient(135deg, #0A192F 0%, #172A45 100%); padding: 15px 30px; color: #FFFFFF; border-bottom: 4px solid #FF6B00; display: flex; justify-content: space-between; align-items: center; }
.banner-left { display: flex; align-items: center; gap: 12px; }
.banner-icon { background: rgba(255, 255, 255, 0.1); width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; border-radius: 6px; font-size: 16px; }
.banner-text h2 { font-size: 18px; font-weight: 600; }
.banner-text p { font-size: 11px; color: #A0AEC0; }
.banner-right-text { font-size: 18px; font-weight: 700; color: rgba(255, 255, 255, 0.15); }
.section-header { display: flex; align-items: center; gap: 8px; padding: 18px 30px 10px 30px; font-size: 14px; font-weight: 600; color: #0A192F; }
.section-header i { color: #FF6B00; font-size: 16px; }
.form-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px 25px; padding: 0 30px; }
.form-group { display: flex; flex-direction: column; }
.form-group label { font-size: 12px; font-weight: 500; color: #2D3748; margin-bottom: 6px; }
.required { color: #E53E3E; margin-left: 3px; }
.input-wrapper { position: relative; display: flex; align-items: center; }
.input-wrapper i { position: absolute; left: 15px; color: #A0AEC0; font-size: 13px; z-index: 2; }
.input-wrapper input, .input-wrapper select { width: 100%; height: 38px; border: 1px solid #E2E8F0; border-radius: 6px; padding: 5px 15px 5px 40px; font-size: 13px; color: #4A5568; background: #FFFFFF; outline: none; }
.input-wrapper textarea { width: 100%; height: 60px; border: 1px solid #E2E8F0; border-radius: 6px; padding: 8px 15px 8px 40px; font-size: 13px; color: #4A5568; resize: none; }
.full-width { grid-column: span 3; }
.form-actions { display: flex; justify-content: flex-end; gap: 12px; padding: 20px 30px 25px 30px; margin-top: auto; border-top: 1px solid #F0F2F5; }
.btn { display: inline-flex; align-items: center; gap: 8px; padding: 8px 22px; border: none; border-radius: 6px; font-size: 13px; font-weight: 500; cursor: pointer; }
.btn-cancel { background: #EDF2F7; color: #4A5568; }
.btn-submit { background: #FF6B00; color: #FFFFFF; }
.sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.4); z-index: 998; }
.alert-box { margin: 10px 30px 0 30px; padding: 8px 15px; border-radius: 6px; font-size: 12px; }
.alert-error { background: #FED7D7; color: #742A2A; border-left: 4px solid #E53E3E; }

@media (min-width: 992px) { body { overflow: hidden; } .page-container { height: calc(100vh - 60px); } }
@media (max-width: 768px) {
    body { overflow-y: auto !important; }
    .mobile-menu-toggle { display: inline-flex; }
    aside, .sidebar, [class*="sidebar"] { left: -260px !important; }
    aside.active, .sidebar.active, [class*="sidebar"].active { left: 0 !important; }
    .content-wrapper { margin-left: 0 !important; width: 100% !important; }
    .form-grid { grid-template-columns: 1fr !important; padding: 0 15px; gap: 12px; }
    .full-width { grid-column: span 1; }
    .form-actions { padding: 15px; justify-content: space-between; }
    .btn { flex: 1; justify-content: center; }
}
</style>
</head>
<body>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileSidebar()"></div>

<div class="main-layout">
    
    <?php 
    if (file_exists($sidebar_path)) { include $sidebar_path; } 
    elseif (file_exists($sidebar_path . ".php")) { include $sidebar_path . ".php"; }
    ?>

    <div class="content-wrapper">
        <div class="top-navbar">
            <div class="navbar-left-flex">
                <div class="mobile-menu-toggle" onclick="toggleMobileSidebar()">
                    <i class="fa-solid fa-bars"></i>
                </div>
                <div class="search-container">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input type="text" placeholder="Search here...">
                </div>
            </div>
            <div class="user-profile">
                <div class="profile-info">
                    <i class="fa-solid fa-circle-user profile-icon"></i>
                    <div class="profile-text">
                        <h4>Rubab Admin</h4>
                        <p>Administrator</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-container">
            <div class="form-card">
                <div class="form-banner">
                    <div class="banner-left">
                        <div class="banner-icon">
                            <i class="fa-solid fa-money-bill-transfer"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Add Transaction</h2>
                            <p>Record business entries and financial ledger movements</p>
                        </div>
                    </div>
                    <div class="banner-right-text">Tameer Al Madina</div>
                </div>
                
                <?php if(isset($error)): ?>
                    <div class='alert-box alert-error'><i class="fa-solid fa-circle-exclamation"></i> <?php echo $error; ?></div>
                <?php endif; ?>

                <form method="POST">
                    <div>
                        <div class="section-header">
                            <i class="fa-solid fa-receipt"></i> Voucher Particulars
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label>Date</label>
                                <div class="input-wrapper">
                                    <i class="fa-regular fa-calendar"></i>
                                    <input type="date" name="date" value="<?php echo date('Y-m-d'); ?>">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Type (Paid/Received)</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-right-left"></i>
                                    <select name="type">
                                        <option value="Paid">Paid</option>
                                        <option value="Received">Received</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Amount (OMR)</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-money-bill-wave"></i>
                                    <input type="number" step="0.001" name="amount" placeholder="0.000">
                                </div>
                            </div>
                        </div>

                        <div class="section-header">
                            <i class="fa-solid fa-route"></i> Account Allocation Mapping
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label>Amount Type (Payment Source)</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-wallet"></i>
                                    <select name="amount_type" id="amount_type">
                                        <option value="" selected>-- Select Payment Source --</option>
                                        <?php if ($accounts_result && $accounts_result->num_rows > 0): ?>
                                            <?php while ($acc = $accounts_result->fetch_assoc()): ?>
                                                <?php 
                                                    $name = $acc['account_name'];
                                                    $sub = strtoupper($acc['sub_type']);
                                                    $icon = (strpos($sub, 'BANK') !== false) ? "🏦 " : "💵 ";
                                                ?>
                                                <option value="<?php echo htmlspecialchars($name); ?>">
                                                    <?php echo $icon . htmlspecialchars($name); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                            <option value="CASH">💵 Default CASH</option>
                                        <?php endif; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Reference Type</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-sitemap"></i>
                                    <select name="reference_type" id="reference_type" onchange="loadReference(this.value)">
                                        <option value="">Select</option>
                                        <option value="customer">Customer</option>
                                        <option value="supplier">Supplier</option>
                                        <option value="EXPENSE">EXPENSE (Kharchay)</option>
                                        <option value="INCOME">INCOME (Sales/Revenue)</option>
                                        <option value="ASSET">ASSET (Cash/Bank accounts)</option>
                                        <option value="EQUITY">EQUITY (Capital Accounts)</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Reference Name</label>
                                <div class="input-wrapper">
                                    <i class="fa-regular fa-address-book"></i>
                                    <select name="reference_id" id="reference_id">
                                        <option value="">Select Category First</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group slide-head full-width">
                                <label>Description</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-align-left"></i>
                                    <textarea name="description" placeholder="Transaction remarks/details..."></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="button" onclick="window.history.back();" class="btn btn-cancel">
                            <i class="fa-solid fa-xmark"></i> Cancel
                        </button>
                        <button type="submit" name="submit" class="btn btn-submit">
                            <i class="fa-regular fa-floppy-disk"></i> Save Transaction
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function loadReference(type){
    const refSelect = document.getElementById("reference_id");
    if(type === "") {
        refSelect.innerHTML = "<option value=''>Select Category First</option>";
        return;
    }
    refSelect.innerHTML = "<option value=''>Loading options...</option>";
    let url = window.location.pathname + "?action=get_reference&type=" + encodeURIComponent(type);

    fetch(url)
        .then(res => {
            if (!res.ok) throw new Error("Network response error");
            return res.text();
        })
        .then(data => { refSelect.innerHTML = data; })
        .catch(err => {
            console.error("Error:", err);
            refSelect.innerHTML = "<option value=''>Error loading references</option>";
        });
}

function toggleMobileSidebar() {
    const sidebarElements = document.querySelectorAll('aside, .sidebar, [class*="sidebar"]');
    const overlay = document.getElementById('sidebarOverlay');
    sidebarElements.forEach(sidebar => sidebar.classList.toggle('active'));
    if(sidebarElements[0] && sidebarElements[0].classList.contains('active')) {
        overlay.style.display = 'block';
    } else {
        overlay.style.display = 'none';
    }
}
</script>
</body>
</html>