<?php
// Output buffering start - Redirection ke liye lazmi hai
ob_start(); 

// Session aur structural components ke liye sidebar ko top par include kiya hai
$sidebar_path = "/home/tameeralmadina/public_html/TAM/sidebar";
if (file_exists($sidebar_path)) {
    include $sidebar_path;
} elseif (file_exists($sidebar_path . ".php")) {
    include $sidebar_path . ".php";
}

include "db.php";

// ========================================================
// 1. DYNAMIC DROPDOWN DATA FETCH (JSON File Se Accounts Read Karna)
// ========================================================
$storage_file = 'accounts_data.json';
$dynamic_accounts = [];

if (file_exists($storage_file)) {
    $file_content = file_get_contents($storage_file);
    $dynamic_accounts = json_decode($file_content, true);
    if (!is_array($dynamic_accounts)) {
        $dynamic_accounts = [];
    }
}

if (isset($_POST['submit'])) {

    $name = $_POST['name'];
    $date = $_POST['date'];
    $amount = floatval($_POST['amount']);
    $currency = !empty($_POST['currency']) ? $_POST['currency'] : 'PKR'; // Rs (PKR) ya OMR
    $type = !empty($_POST['type']) ? $_POST['type'] : 'Paid'; 
    $amount_type = $_POST['amount_type']; // Isme dynamic account ka title/name save hoga
    $description = $_POST['description'];

    // 1. Prepared Statement for Expense Table
    $stmt1 = $conn->prepare("INSERT INTO expense (name, date, amount, currency, type, amount_type, description) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt1->bind_param("ssdssss", $name, $date, $amount, $currency, $type, $amount_type, $description);

    if ($stmt1->execute()) {
        
        $expense_id = intval($conn->insert_id);
        $stmt1->close();

        // Database enum constraints ke mutabiq values variables mein define karke execute kar rahe hain
        $tx_type = 'DEBIT';
        $ref_type = 'EXPENSE';

        // 2. Prepared Statement for Transactions Table
        $stmt2 = $conn->prepare("INSERT INTO transactions (date, type, amount, currency, amount_type, reference_id, reference_type, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        
        // Total 8 parameters match ho rahe hain
        $stmt2->bind_param("ssdssiss", $date, $tx_type, $amount, $currency, $amount_type, $expense_id, $ref_type, $description);
        $stmt2->execute();
        $stmt2->close();
        
        // 3. Safe Redirect - buffer clear karke phir header bhejna
        if (ob_get_length()) {
            ob_end_clean();
        }

        if (!headers_sent()) {
            header("Location: expense_view.php");
            exit();
        } else {
            // Fallback agar headers already send ho chuke hon
            echo "<script>window.location.href='expense_view.php';</script>";
            exit();
        }

    } else {
        $error = "Error saving expense: " . $stmt1->error;
        $stmt1->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Expense - 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;
}

/* Navbar Architecture */
.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;
}

/* No Admon avatar image source - clean Vector icon mapping used */
.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;
}

/* Form Container Structures */
.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;
}

/* Fluid 3-Column Grid setup */
.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: 38px; 
    border: 1px solid #E2E8F0;
    border-radius: 6px;
    padding: 8px 15px 8px 40px;
    font-size: 13px;
    color: #4A5568;
    resize: none;
}

.input-wrapper input:focus,
.input-wrapper select:focus,
.input-wrapper textarea:focus {
    border-color: #FF6B00;
    box-shadow: 0 0 0 2px rgba(255, 107, 0, 0.1);
    outline: none;
}

.full-width {
    grid-column: span 3;
}

.alert-container {
    padding: 15px 30px 0 30px;
}

.alert {
    padding: 10px 15px;
    border-radius: 6px;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.alert-error { background: #FFF5F5; border: 1px solid #FED7D7; color: #E53E3E; }

.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;
}

/* Breakpoint Configuration */
@media (min-width: 992px) {
    body { overflow: hidden; }
    .page-container { height: calc(100vh - 60px); }
}

@media (max-width: 1024px) and (min-width: 769px) {
    aside, .sidebar, [class*="sidebar"] { width: 240px; min-width: 240px; }
    .content-wrapper { margin-left: 240px; width: calc(100% - 240px); }
    .form-grid { grid-template-columns: repeat(2, 1fr); }
    .full-width { grid-column: span 2; }
}

@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; }
    .top-navbar { padding: 0 15px; }
    .search-container { width: 140px; }
    .page-container { padding: 10px; }
    .form-banner { padding: 12px 15px; }
    .banner-right-text { display: none; }
    .section-header { padding: 15px 15px 8px 15px; }
    .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> 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-wallet"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Add Expense</h2>
                            <p>Log official business outflows and operational expenses</p>
                        </div>
                    </div>
                    <div class="banner-right-text">Tameer Al Madina</div>
                </div>

                <?php if(isset($error)): ?>
                    <div class="alert-container">
                        <div class="alert alert-error">
                            <i class="fa-solid fa-triangle-exclamation"></i> <?= htmlspecialchars($error) ?>
                        </div>
                    </div>
                <?php endif; ?>

                <form method="POST">
                    
                    <div>
                        <div class="section-header">
                            <i class="fa-solid fa-file-invoice-dollar"></i> Expense Metrics
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label>Expense Name<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-tags"></i>
                                    <input type="text" name="name" required placeholder="e.g. Utility Bills">
                                </div>
                            </div>

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

                            <div class="form-group">
                                <label>Amount<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-dollar-sign" id="amountIcon"></i>
                                    <input type="number" step="0.01" name="amount" id="amountInput" placeholder="0.00" required>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Currency<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-money-bill-transfer"></i>
                                    <select name="currency" id="currencySelect" onchange="updateAmountFormat()" required>
                                        <option value="PKR" selected>PKR - Rs (Pakistani Rupee)</option>
                                        <option value="OMR">OMR (Omani Rial)</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="section-header">
                            <i class="fa-solid fa-money-check-dollar"></i> Execution & Source Account
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label>Type</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 Type (Payment Source)<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-building-columns"></i>
                                    <select name="amount_type" required>
                                        <option value="" selected disabled>-- Select Payment Source --</option>
                                        
                                        <?php if (!empty($dynamic_accounts)): ?>
                                            <?php foreach ($dynamic_accounts as $account): ?>
                                                <?php 
                                                    if (isset($account['type']) && $account['type'] === 'BANK') {
                                                        $value = $account['bank_name'] . " (" . $account['account_number'] . ")";
                                                        $display_name = "🏦 " . $account['bank_name'] . " - " . $account['account_number'];
                                                    } else {
                                                        $value = $account['description'];
                                                        $display_name = "💵 " . $account['description'];
                                                    }
                                                ?>
                                                <option value="<?php echo htmlspecialchars($value); ?>">
                                                    <?php echo htmlspecialchars($display_name); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <option value="CASH">💵 Default CASH</option>
                                            <option value="BANK">🏦 Default BANK</option>
                                        <?php endif; ?>
                                        
                                    </select>
                                </div>
                            </div>

                            <div class="form-group full-width">
                                <label>Description</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-align-left"></i>
                                    <textarea name="description" placeholder="Write additional expense summary context..."></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> Add Expense
                        </button>
                    </div>

                </form>

            </div>
        </div>
    </div>
</div>

<script>
function updateAmountFormat() {
    var currencySelect = document.getElementById("currencySelect");
    var amountInput = document.getElementById("amountInput");
    var amountIcon = document.getElementById("amountIcon");

    if (currencySelect.value === "OMR") {
        // OMR mein 3 decimal places hote hain (e.g. 0.000)
        amountInput.step = "0.001";
        amountInput.placeholder = "0.000";

        // Dollar sign hata kar generic currency icon laga rahe hain
        amountIcon.classList.remove("fa-dollar-sign");
        amountIcon.classList.add("fa-coins");

        // Agar pehle se koi value likhi hai to usay 3 decimals mein round kar dein
        if (amountInput.value !== "") {
            amountInput.value = parseFloat(amountInput.value).toFixed(3);
        }
    } else {
        // PKR (Rs) mein 2 decimal places
        amountInput.step = "0.01";
        amountInput.placeholder = "0.00";

        amountIcon.classList.remove("fa-coins");
        amountIcon.classList.add("fa-dollar-sign");

        if (amountInput.value !== "") {
            amountInput.value = parseFloat(amountInput.value).toFixed(2);
        }
    }
}

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].classList.contains('active')) {
        overlay.style.display = 'block';
    } else {
        overlay.style.display = 'none';
    }
}
</script>

</body>
</html>