<?php
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'auth.php';
include "db.php";

// --- DELETE LOGIC ---
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $delete_query = "DELETE FROM transactions WHERE id = ? AND type = 'Debit'";
    $stmt = $conn->prepare($delete_query);
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        header("Location: " . basename($_SERVER['PHP_SELF']));
        exit;
    }
}

/* 📊 TRANSACTIONS TABLE SE SALES INVOICES NIKALNA */
$sales_query = "
    SELECT 
        t.id as invoice_id, 
        t.date,
        t.reference_id as customer_id,
        c.name as customer_name,
        t.description,
        t.amount
    FROM transactions t
    LEFT JOIN customers c ON t.reference_id = c.id
    WHERE t.reference_type = 'customer' AND t.type = 'Debit'
    ORDER BY t.date DESC, t.id DESC
";

$result = $conn->query($sales_query);
$sales = [];

if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()){
        $sales[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sales Invoice 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;
}

/* Master Fixed Left Sidebar Layout */
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;
}

/* System Top Headers Section */
.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 Fluid Workspace Content */
.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-banner {
    background: linear-gradient(135deg, #0A192F 0%, #172A45 100%);
    padding: 15px 30px;
    color: #FFFFFF;
    border-bottom: 4px solid #ff6a00; /* Orange Global Accent Line */
    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;
}

/* Add Sale Action Button */
.btn-add-new {
    background: linear-gradient(135deg, #ffb03a, #ff7b00);
    color: #fff;
    padding: 8px 18px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 600;
    font-size: 13px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: 0.3s;
    box-shadow: 0 3px 10px rgba(255,176,58,0.2);
}

.btn-add-new:hover {
    transform: translateY(-1px);
    opacity: 0.95;
}

/* Master Desktop Data Grid Layout */
.table-responsive {
    padding: 20px 30px;
    width: 100%;
    overflow-x: auto;
    display: block;
}

table {
    width: 100%;
    border-collapse: collapse;
}

table thead {
    background: linear-gradient(90deg, #0f2357, #172a45);
}

table th {
    padding: 14px;
    font-size: 13px;
    font-weight: 600;
    color: #FFFFFF;
    text-align: left;
    letter-spacing: 0.5px;
}

table th:first-child { border-top-left-radius: 6px; border-bottom-left-radius: 6px; }
table th:last-child { border-top-right-radius: 6px; border-bottom-right-radius: 6px; }

table td {
    padding: 14px;
    border-bottom: 1px solid #E2E8F0;
    font-size: 13px;
    color: #334155;
    background: #FFFFFF;
    vertical-align: middle;
}

table tbody tr:hover td {
    background: #F8FAFC;
}

.amount-text {
    font-weight: 700;
    color: #1e293b;
}

/* Action Utility Buttons Styling */
.actions-group {
    display: flex;
    gap: 6px;
    align-items: center;
    flex-wrap: nowrap;
}

.btn-action {
    padding: 6px 12px;
    border-radius: 5px;
    text-decoration: none;
    font-size: 11px;
    font-weight: 600;
    transition: 0.2s;
    white-space: nowrap;
    color: #fff;
    display: inline-block;
}

.btn-invoice { background: #28a745; }
.btn-invoice:hover { background: #1e7e34; }

.btn-view { background: #007bff; }
.btn-view:hover { background: #0056b3; }

.btn-return { background: #dc3545; }
.btn-return:hover { background: #bd2130; }

/* New Delete Button Style */
.btn-delete { background: #6b7280; }
.btn-delete:hover { background: #4b5563; }

/* Mobile Card View Structure */
.mobile-cards-container {
    display: none;
    padding: 15px;
    flex-direction: column;
    gap: 12px;
}

.mobile-card {
    background: #FFFFFF;
    border-radius: 10px;
    padding: 15px;
    border: 1px solid #E2E8F0;
    box-shadow: 0 2px 5px rgba(0,0,0,0.02);
}

.card-header-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px dashed #E2E8F0;
    padding-bottom: 8px;
    margin-bottom: 10px;
}

.card-title-main {
    font-weight: 700;
    color: #0A192F;
    font-size: 14px;
}

.card-date-badge {
    font-size: 11px;
    color: #64748b;
    background: #F1F5F9;
    padding: 3px 8px;
    border-radius: 4px;
    font-weight: 500;
}

.card-body-details {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-bottom: 12px;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
}

.detail-row .label { color: #64748b; }
.detail-row .value { color: #334155; font-weight: 500; }

.card-amount-total {
    font-size: 14px;
    font-weight: 700;
    color: #ff6a00;
}

.card-actions-wrapper {
    border-top: 1px solid #F1F5F9;
    padding-top: 10px;
    display: flex;
    justify-content: flex-start;
}

.no-data {
    text-align: center;
    padding: 40px;
    color: #64748b;
    font-size: 14px;
    font-style: italic;
}

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

@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: 15px; flex-direction: column; gap: 12px; align-items: flex-start; }
    .btn-add-new { width: 100%; justify-content: center; }
    
    /* View Switch Responsive Toggles */
    .table-responsive { display: none; }
    .mobile-cards-container { display: flex; }
}
</style>
</head>
<body>

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

<div class="main-layout">
    
    <?php 
    $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";
    }
    ?>

    <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 invoices...">
                </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-file-invoice-dollar"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Sales Invoices List</h2>
                            <p>Track customer ledger bookings, structural debit entries, and perform material balance returns</p>
                        </div>
                    </div>
                    <a href="sales_add.php" class="btn-add-new">
                        <i class="fa-solid fa-plus"></i> Add Sale
                    </a>
                </div>

                <div class="table-responsive">
                    <table id="salesTable">
                    <thead>
                        <tr>
                            <th style="width: 12%;">Date</th>
                            <th style="width: 25%;">Customer Name</th>
                            <th style="width: 25%;">Description</th>
                            <th style="width: 12%;">Grand Total</th>
                            <th style="width: 26%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if(count($sales) > 0){
                            foreach($sales as $row){
                                $formatted_date = date('d M Y', strtotime($row['date']));
                                $customer_name = !empty($row['customer_name']) ? htmlspecialchars($row['customer_name']) : "Unknown Customer";
                                
                                $desc_data = json_decode($row['description'], true);
                                if (json_last_error() === JSON_ERROR_NONE) {
                                    $description = "<em>Itemized Invoice Statement</em>";
                                } else {
                                    $description = htmlspecialchars($row['description']);
                                }
                                
                                $amount = number_format($row['amount'], 3);
                                
                                $ledger_link = "ledger_view.php?type=customer&id=" . $row['customer_id'];
                                $invoice_link = "invoice_view.php?id=" . $row['invoice_id'];
                                $return_link = "sales_return.php?id=" . $row['invoice_id'];

                                echo "<tr>
                                    <td><strong>{$formatted_date}</strong></td>
                                    <td><span style='color: #0A192F; font-weight: 600;'>{$customer_name}</span></td>
                                    <td>{$description}</td>
                                    <td class='amount-text'>{$amount} OMR</td>
                                    <td>
                                        <div class='actions-group'>
                                            <a href='{$invoice_link}' class='btn-action btn-invoice' title='View Invoice'><i class='fa-solid fa-eye'></i></a>
                                            <a href='{$ledger_link}' class='btn-action btn-view' title='View Ledger'><i class='fa-solid fa-book'></i></a>
                                            <a href='{$return_link}' class='btn-action btn-return' title='Sales Return'><i class='fa-solid fa-rotate-left'></i></a>
                                            <a href='?delete_id={$row['invoice_id']}' class='btn-action btn-delete' title='Delete' onclick='return confirm(\"Are you sure you want to delete this invoice?\");'><i class='fa-solid fa-trash'></i></a>
                                        </div>
                                    </td>
                                </tr>";
                            }
                        } else {
                            echo "<tr><td colspan='5' class='no-data'>No Sales Invoices Found.</td></tr>";
                        }
                        ?>
                    </tbody>
                    </table>
                </div>

                <div class="mobile-cards-container">
                    <?php
                    if(count($sales) > 0){
                        foreach($sales as $row){
                            $formatted_date = date('d M Y', strtotime($row['date']));
                            $customer_name = !empty($row['customer_name']) ? htmlspecialchars($row['customer_name']) : "Unknown Customer";
                            $amount = number_format($row['amount'], 3);
                            
                            $ledger_link = "ledger_view.php?type=customer&id=" . $row['customer_id'];
                            $invoice_link = "invoice_view.php?id=" . $row['invoice_id'];
                            $return_link = "sales_return.php?id=" . $row['invoice_id'];
                            ?>
                            <div class="mobile-card">
                                <div class="card-header-flex">
                                    <span class="card-title-main"><?php echo $customer_name; ?></span>
                                    <span class="card-date-badge"><?php echo $formatted_date; ?></span>
                                </div>
                                <div class="card-body-details">
                                    <div class="detail-row" style="margin-top: 4px; border-top: 1px solid #F1F5F9; padding-top: 4px;">
                                        <span class="label" style="font-weight: 600;">Total Amount:</span>
                                        <span class="card-amount-total"><?php echo $amount; ?> OMR</span>
                                    </div>
                                </div>
                                <div class="card-actions-wrapper">
                                    <div class="actions-group">
                                        <a href="<?php echo $invoice_link; ?>" class="btn-action btn-invoice">View</a>
                                        <a href="<?php echo $ledger_link; ?>" class="btn-action btn-view">Ledger</a>
                                        <a href="<?php echo $return_link; ?>" class="btn-action btn-return">Return</a>
                                        <a href="?delete_id=<?php echo $row['invoice_id']; ?>" class="btn-action btn-delete" onclick="return confirm('Are you sure?');">Delete</a>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                    } else {
                        echo '<div class="no-data">No Sales Invoices Found.</div>';
                    }
                    ?>
                </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>