<?php
include "db.php";
$sidebar_path = "/home/tameeralmadina/public_html/TAM/sidebar";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Transactions List - 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; }
.table-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; }
.table-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 { display: flex; align-items: center; gap: 10px; }
.add-btn { background: #FF6B00; color: #FFFFFF; text-decoration: none; padding: 8px 16px; font-size: 12px; font-weight: 500; border-radius: 6px; display: inline-flex; align-items: center; gap: 6px; transition: background 0.2s; }
.add-btn:hover { background: #e05e00; }
.table-responsive { width: 100%; overflow-x: auto; padding: 15px 20px; }
table { width: 100%; border-collapse: collapse; background: #FFFFFF; border-radius: 8px; overflow: hidden; }
th { background: #F8F9FA; color: #4A5568; font-weight: 600; font-size: 12px; padding: 12px 15px; text-align: left; border-bottom: 2px solid #E2E8F0; text-transform: uppercase; letter-spacing: 0.5px; }
td { padding: 12px 15px; font-size: 13px; color: #4A5568; border-bottom: 1px solid #EDF2F7; }
tr:hover { background: #F8FAFC; }
.badge { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; text-align: center; }
.badge-paid { background: #FED7D7; color: #C53030; }
.badge-received { background: #C6F6D5; color: #22543D; }
.badge-type { background: #E2E8F0; color: #4A5568; font-size: 11px; }
.action-links a { text-decoration: none; color: #4A5568; font-weight: 500; font-size: 12px; padding: 4px 8px; border-radius: 4px; display: inline-flex; align-items: center; gap: 4px; transition: all 0.2s; }
.action-edit { background: #EBF8FF; color: #2B6CB0 !important; }
.action-edit:hover { background: #BEE3F8; }
.action-delete { background: #FFF5F5; color: #C53030 !important; }
.action-delete:hover { background: #FED7D7; }
.sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.4); z-index: 998; }

@media (max-width: 768px) {
    .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; }
    .page-container { padding: 15px; }
    .table-banner { padding: 15px; }
}
</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 transactions...">
                </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="table-card">
                <div class="table-banner">
                    <div class="banner-left">
                        <div class="banner-icon">
                            <i class="fa-solid fa-list-check"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Transactions Registry</h2>
                            <p>Overview of all financial inflows and outflows</p>
                        </div>
                    </div>
                    <div class="banner-right">
                        <a href="transactions.php" class="add-btn">
                            <i class="fa-solid fa-plus"></i> Add New
                        </a>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Amount</th>
                                <th>Source</th>
                                <th>Category</th>
                                <th>Reference Mapping</th>
                                <th>Description</th>
                                <th style="text-align: center;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php
                        // Safely handles all lookups. If reference table join yields empty name, it dynamically checks description or puts 'General Entry'
                        $query = "
                        SELECT 
                            t.id,
                            t.date,
                            CASE 
                                WHEN UPPER(t.type) IN ('PAID', 'DEBIT') THEN 'Paid'
                                WHEN UPPER(t.type) IN ('RECEIVED', 'CREDIT') THEN 'Received'
                                ELSE t.type
                            END AS txn_type,
                            t.amount,
                            t.amount_type,
                            IFNULL(t.reference_type,'GENERAL') AS reference_type,
                            CASE
                                WHEN UPPER(t.reference_type)='CUSTOMER'  THEN IFNULL(c.name, 'Customer Account')
                                WHEN UPPER(t.reference_type)='SUPPLIER'  THEN IFNULL(s.name, 'Supplier Account')
                                WHEN UPPER(t.reference_type)='EXPENSE'   THEN IFNULL(e.name, 'Expense Head')
                                WHEN UPPER(t.reference_type)='INVENTORY' THEN IFNULL(i.name, 'Inventory Item')
                                WHEN UPPER(t.reference_type)='CASH'      THEN 'Cash Account'
                                WHEN UPPER(t.reference_type)='BANK'      THEN IFNULL(b.bank_name, 'Bank Account')
                                ELSE 'General Head'
                            END AS reference_name,
                            t.description
                        FROM transactions t
                        LEFT JOIN customers  c   ON t.reference_id=c.id
                        LEFT JOIN suppliers  s   ON t.reference_id=s.id
                        LEFT JOIN expense    e   ON t.reference_id=e.id
                        LEFT JOIN inventory  i   ON t.reference_id=i.id
                        LEFT JOIN bank       b   ON t.reference_id=b.id
                        ORDER BY t.id DESC
                        ";

                        $result = $conn->query($query);

                        if ($result && $result->num_rows > 0) {
                            while ($row = $result->fetch_assoc()) {
                                $type_badge = ($row['txn_type'] === 'Paid') ? 'badge-paid' : 'badge-received';
                                
                                // Fallback mapping check if it was raw chart of accounts reference string parsed in description
                                $final_ref_name = $row['reference_name'];
                                if(($final_ref_name === 'General Head' || empty($final_ref_name)) && !empty($row['description'])){
                                    if(preg_strict_match('/\[Account:\s*(.*?)\]/', $row['description'], $matches)){
                                        $final_ref_name = $matches[1];
                                    }
                                }

                                echo "<tr>
                                    <td><strong>#{$row['id']}</strong></td>
                                    <td>" . date('d-M-Y', strtotime($row['date'])) . "</td>
                                    <td><span class='badge {$type_badge}'>{$row['txn_type']}</span></td>
                                    <td><strong>OMR " . number_format($row['amount'], 3) . "</strong></td>
                                    <td><span class='badge badge-type'>{$row['amount_type']}</span></td>
                                    <td>" . ucfirst(strtolower($row['reference_type'])) . "</td>
                                    <td>" . htmlspecialchars($final_ref_name) . "</td>
                                    <td>" . htmlspecialchars($row['description']) . "</td>
                                    <td class='action-links' style='text-align: center;'>
                                        <a href='transactions_edit.php?id={$row['id']}' class='action-edit'><i class='fa-regular fa-pen-to-square'></i> Edit</a>
                                        <a href='transactions_delete.php?id={$row['id']}' class='action-delete' onclick='return confirm(\"Are you sure you want to delete this log?\")'><i class='fa-regular fa-trash-can'></i> Delete</a>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='9' style='text-align:center; padding: 30px; color: #A0AEC0;'>No Transactions Registered Found. Please check if 'transactions' table has records.</td></tr>";
                        }

                        // Helper function inline context setup
                        function preg_strict_match($pattern, $subject, &$matches) {
                            return preg_match($pattern, $subject, $matches);
                        }
                        ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
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>