<?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']);
    // Note: This deletes the transaction entry.
    $delete_query = "DELETE FROM transactions WHERE id = ? AND type = 'Credit'";
    $stmt = $conn->prepare($delete_query);
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        header("Location: " . basename($_SERVER['PHP_SELF']));
        exit;
    }
}

/* 📊 TRANSACTIONS TABLE SE PURCHASES INVOICES NIKALNA */
$purchase_query = "
    SELECT 
        t.id as transaction_id,
        p.id as purchase_id, 
        t.date,
        t.reference_id as supplier_id,
        s.name as supplier_name,
        t.description,
        t.amount
    FROM transactions t
    LEFT JOIN suppliers s ON t.reference_id = s.id
    LEFT JOIN purchases p ON (p.supplier_id = t.reference_id AND DATE(p.purchase_date) = DATE(t.date) AND p.grand_total = t.amount)
    WHERE t.reference_type = 'supplier' AND t.type = 'Credit'
    ORDER BY t.date DESC, t.id DESC
";

$result = $conn->query($purchase_query);
$purchases = [];

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

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

.btn-add-account {
    background: #0f2357;
    color: #FFFFFF;
    padding: 8px 18px;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 500;
    font-size: 13px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;
    box-shadow: 0 2px 6px rgba(15, 35, 87, 0.15);
    border: 1px solid rgba(255,255,255,0.1);
}

.btn-add-account:hover {
    background: #091636;
    transform: translateY(-1px);
}

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

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

table thead {
    background: #0f2357;
}

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

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

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

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

.amount-cell {
    font-weight: 700;
    color: #1a202c;
}

/* Unified Layout Operational Actions Button Controls */
.actions-group {
    display: flex;
    gap: 6px;
    align-items: center;
}

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

.btn-bill { background: #10b981; }
.btn-bill:hover { background: #059669; }

.btn-view { background: #3b82f6; }
.btn-view:hover { background: #2563eb; }

.btn-return { background: #ef4444; }
.btn-return:hover { background: #dc2626; }

.btn-delete { background: #6b7280; }
.btn-delete:hover { background: #4b5563; }

.no-data {
    text-align: center;
    color: #64748b;
    padding: 35px;
    font-style: italic;
    font-size: 13px;
    background-color: #f8fafc;
    border-radius: 6px;
    border: 1px dashed #cbd5e1;
}

/* Mobile View Responsive Cards Layout */
.mobile-cards-container {
    display: none;
    padding: 20px 20px;
    flex-direction: column;
    gap: 12px;
}

.mobile-card {
    background: #FFFFFF;
    border-radius: 8px;
    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: #0f2357;
    font-size: 14px;
}

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

.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-big {
    font-size: 13px;
    font-weight: 700;
    color: #1a202c;
}

.mobile-actions-wrapper {
    margin-top: 12px;
    padding-top: 10px;
    border-top: 1px solid #f1f5f9;
}

.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: 12px 15px; flex-direction: column; gap: 15px; align-items: flex-start; }
    .btn-add-account { width: 100%; justify-content: center; }
    
    .table-responsive { display: none; }
    .mobile-cards-container { display: flex; }
    .mobile-actions-wrapper .actions-group { justify-content: space-between; }
    .mobile-actions-wrapper .btn-action { flex: 1; text-align: center; }
}
</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 parameters 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-receipt"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Purchase Invoices List</h2>
                            <p>&nbsp;Manage, audit, and return raw material stock purchases and supplier invoices seamlessly</p>
                        </div>
                    </div>
                    <a href="add-purchase.php" class="btn-add-account">
                        <i class="fa-solid fa-plus"></i> Add Purchase
                    </a>
                </div>
                
                <div class="table-responsive">
                    <?php if (empty($purchases)): ?>
                        <div class="no-data">No Purchase Records Found.</div>
                    <?php else: ?>
                        <table>
                            <thead>
                                <tr>
                                    <th style="width: 12%;">Date</th>
                                    <th style="width: 20%;">Supplier Name</th>
                                    <th style="width: 25%;">Description</th>
                                    <th style="width: 13%;">Total Amount</th>
                                    <th style="width: 30%; text-align: center;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($purchases as $row): 
                                    $formatted_date = date('d-M-Y', strtotime($row['date']));
                                    $raw_supplier = $row['supplier_name'] ?? '';
                                    $supplier_name = !empty($raw_supplier) ? htmlspecialchars($raw_supplier) : "Unknown Supplier";
                                    
                                    $raw_desc = $row['description'] ?? '';
                                    $desc_data = json_decode($raw_desc, true);
                                    if (json_last_error() === JSON_ERROR_NONE && !empty($raw_desc)) {
                                        $description = "Itemized Stock Purchase Invoice";
                                    } else {
                                        $description = htmlspecialchars($raw_desc);
                                    }
                                    $amount = number_format($row['amount'], 2);
                                    
                                    $ledger_link = "ledger_view.php?type=supplier&id=" . $row['supplier_id'];
                                    $target_id = !empty($row['purchase_id']) ? $row['purchase_id'] : 1; 
                                    $bill_link = "purchase_view.php?id=" . $target_id;
                                    $return_link = "purchase_return.php?id=" . $target_id;
                                ?>
                                    <tr>
                                        <td><strong><?php echo $formatted_date; ?></strong></td>
                                        <td><span style="color: #0f2357; font-weight: 600;"><?php echo $supplier_name; ?></span></td>
                                        <td><?php echo $description; ?></td>
                                        <td class="amount-cell"><?php echo $amount; ?> PKR</td>
                                        <td>
                                            <div class="actions-group">
                                                <a href="<?php echo $bill_link; ?>" class="btn-action btn-bill">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['transaction_id']; ?>" class="btn-action btn-delete" onclick="return confirm('Are you sure you want to delete this record?');">Delete</a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <div class="mobile-cards-container">
                    <?php if (empty($purchases)): ?>
                        <div class="no-data">No Purchase Records Found.</div>
                    <?php else: ?>
                        <?php foreach ($purchases as $row): 
                            $formatted_date = date('d-M-Y', strtotime($row['date']));
                            $raw_supplier = $row['supplier_name'] ?? '';
                            $supplier_name = !empty($raw_supplier) ? htmlspecialchars($raw_supplier) : "Unknown Supplier";
                            
                            $raw_desc = $row['description'] ?? '';
                            $desc_data = json_decode($raw_desc, true);
                            if (json_last_error() === JSON_ERROR_NONE && !empty($raw_desc)) {
                                $description = "Itemized Stock Purchase Invoice";
                            } else {
                                $description = htmlspecialchars($raw_desc);
                            }
                            $amount = number_format($row['amount'], 2);
                            
                            $ledger_link = "ledger_view.php?type=supplier&id=" . $row['supplier_id'];
                            $target_id = !empty($row['purchase_id']) ? $row['purchase_id'] : 1; 
                            $bill_link = "purchase_view.php?id=" . $target_id;
                            $return_link = "purchase_return.php?id=" . $target_id;
                        ?>
                            <div class="mobile-card">
                                <div class="card-header-flex">
                                    <span class="card-title-main"><?php echo $supplier_name; ?></span>
                                    <span class="card-amount-big"><?php echo $amount; ?> PKR</span>
                                </div>
                                <div class="card-body-details">
                                    <div class="detail-row">
                                        <span class="label">Date:</span>
                                        <span class="value"><?php echo $formatted_date; ?></span>
                                    </div>
                                    <div class="detail-row">
                                        <span class="label">Details:</span>
                                        <span class="value"><?php echo $description; ?></span>
                                    </div>
                                </div>
                                <div class="mobile-actions-wrapper">
                                    <div class="actions-group">
                                        <a href="<?php echo $bill_link; ?>" class="btn-action btn-bill">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['transaction_id']; ?>" class="btn-action btn-delete" onclick="return confirm('Are you sure?');">Delete</a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </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>