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

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

/* 🗑️ DELETE HANDLER: DELETE QUOTATION & ITS ITEMS */
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $delete_id = intval($_GET['id']);
    
    // Parent quotation delete karne se foreign key cascade automatic items ko bhi delete kar dega
    $stmt_del = $conn->prepare("DELETE FROM quotations WHERE id = ?");
    $stmt_del->bind_param("i", $delete_id);
    if ($stmt_del->execute()) {
        header("Location: quote_list.php");
        exit();
    } else {
        echo "<script>alert('Error deleting quotation: " . $conn->error . "');</script>";
    }
    $stmt_del->close();
}

/* 🔥 CONFIRMATION HANDLER: CONVERT QUOTATION TO REAL INVOICE */
if (isset($_GET['action']) && $_GET['action'] === 'confirm' && isset($_GET['id'])) {
    $quote_id = intval($_GET['id']);
    
    // Fetch Quotation Meta Data
    $q_master = $conn->query("SELECT * FROM quotations WHERE id = $quote_id AND status = 'Pending'")->fetch_assoc();
    
    if ($q_master) {
        $customer_id = $q_master['customer_id'];
        $date = date('Y-m-d'); 
        $summary_json = $q_master['summary_data'];
        $grand_total = $q_master['amount'];
        
        $type = "Debit"; 
        $reference_type = "customer";

        // Insert into transactions (Ledger Hit)
        $stmt_trans = $conn->prepare("INSERT INTO transactions (reference_id, reference_type, date, description, type, amount) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt_trans->bind_param("issssd", $customer_id, $reference_type, $date, $summary_json, $type, $grand_total);
        
        if ($stmt_trans->execute()) {
            $new_sale_id = $stmt_trans->insert_id;

            // Fetch Items
            $q_items = $conn->query("SELECT * FROM quotation_items WHERE quotation_id = $quote_id")->fetch_all(MYSQLI_ASSOC);
            
            // Insert into sale_items
            $stmt_item = $conn->prepare("INSERT INTO sale_items (transaction_id, product_id, quantity, price, total) VALUES (?, ?, ?, ?, ?)");
            foreach ($q_items as $item) {
                $stmt_item->bind_param("iiidd", $new_sale_id, $item['product_id'], $item['quantity'], $item['price'], $item['total']);
                $stmt_item->execute();
            }
            $stmt_item->close();

            // Update Quotation Status
            $conn->query("UPDATE quotations SET status = 'Confirmed' WHERE id = $quote_id");

            header("Location: invoice_view.php?id=" . $new_sale_id);
            exit();
        }
    }
}

/* Fetch Quotations Data List */
$list_query = "SELECT q.*, c.name as customer_name FROM quotations q LEFT JOIN customers c ON q.customer_id = c.id ORDER BY q.id DESC";
$quotes = $conn->query($list_query)->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sales Estimates & Quotations - Tameer Al Madina</title>
<link href="https://fonts.googleapis.com/css2?family=Inter: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: #F8FAFC;
    font-family: 'Inter', sans-serif;
    color: #1E293B;
    min-height: 100vh;
}

.main-layout {
    display: flex;
    width: 100%;
    min-height: 100vh;
    position: relative;
}

/* Fixed Sidebar Baseline */
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: #F8FAFC;
    min-width: 0;
    width: calc(100% - 260px);
    transition: all 0.3s ease;
}

/* Top Unified Dashboard Navbar Header */
.top-navbar {
    height: 70px;
    background: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 40px;
    border-bottom: 1px solid #E2E8F0;
}

.navbar-left-flex {
    display: flex;
    align-items: center;
    gap: 15px;
}

.mobile-menu-toggle {
    display: none;
    font-size: 18px;
    color: #334155;
    cursor: pointer;
    background: #F1F5F9;
    width: 40px;
    height: 40px;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    border: 1px solid #E2E8F0;
    transition: 0.2s;
}

.mobile-menu-toggle:hover {
    background: #E2E8F0;
}

.search-container {
    position: relative;
    width: 320px;
}

.search-container input {
    width: 100%;
    padding: 10px 16px 10px 42px;
    background: #F1F5F9;
    border: 1px solid transparent;
    border-radius: 10px;
    font-size: 14px;
    color: #1E293B;
    outline: none;
    transition: all 0.2s ease;
}

.search-container input:focus {
    background: #FFFFFF;
    border-color: #CBD5E1;
    box-shadow: 0 0 0 3px rgba(148, 163, 184, 0.1);
}

.search-container i {
    position: absolute;
    left: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: #94A3B8;
    font-size: 14px;
}

.user-profile {
    display: flex;
    align-items: center;
    gap: 20px;
}

.profile-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.profile-info i.profile-icon {
    font-size: 20px;
    color: #475569;
    background: #F1F5F9;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    border: 1px solid #E2E8F0;
}

.profile-text h4 {
    font-size: 14px;
    color: #0F172A;
    font-weight: 600;
}

.profile-text p {
    font-size: 12px;
    color: #64748B;
}

/* Page Workspace Panel */
.page-container {
    padding: 30px 40px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.form-card {
    background: #FFFFFF;
    border-radius: 16px;
    border: 1px solid #E2E8F0;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
    overflow: hidden;
    width: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
}

.form-banner {
    background: #0F172A;
    padding: 24px 35px;
    color: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #1E293B;
}

.banner-left {
    display: flex;
    align-items: center;
    gap: 16px;
}

.banner-icon {
    background: rgba(255, 255, 255, 0.08);
    width: 46px;
    height: 46px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 20px;
    color: #38BDF8;
}

.banner-text h2 {
    font-size: 20px;
    font-weight: 600;
    letter-spacing: -0.5px;
}

.banner-text p {
    font-size: 13px;
    color: #94A3B8;
    margin-top: 2px;
}

/* Primary Action Button */
.btn-add {
    background: #38BDF8;
    color: #0F172A;
    padding: 10px 20px;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;
}

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

/* Desktop Grid System */
.table-responsive {
    padding: 24px 35px;
    width: 100%;
    overflow-x: auto;
}

table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}

table th {
    padding: 16px;
    font-size: 13px;
    font-weight: 600;
    color: #475569;
    text-align: left;
    background: #F8FAFC;
    border-bottom: 1px solid #E2E8F0;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

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

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

/* Operational Action Utilities Alignment */
.actions-group {
    display: flex;
    gap: 8px;
    align-items: center;
}

.btn-action {
    width: 34px;
    height: 34px;
    border-radius: 8px;
    text-decoration: none;
    font-size: 13px;
    transition: all 0.2s ease;
    color: #fff;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: none;
    cursor: pointer;
}

.btn-view { background: #0284C7; color: #FFFFFF; } .btn-view:hover { background: #0369A1; }
.btn-confirm { background: #16A34A; color: #FFFFFF; } .btn-confirm:hover { background: #15803D; }
.btn-attach { background: #475569; color: #FFFFFF; } .btn-attach:hover { background: #334155; }
.btn-delete { background: #DC2626; color: #FFFFFF; } .btn-delete:hover { background: #B91C1C; }

/* Refined Badges Architecture */
.status-badge {
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
}
.status-Pending { background: #FEF3C7; color: #D97706; }
.status-Confirmed { background: #DCFCE7; color: #16A34A; }

.converted-badge {
    color: #16A34A;
    font-size: 13px;
    font-weight: 600;
    background: #DCFCE7;
    width: 34px;
    height: 34px;
    border-radius: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

/* Mobile Setup Layout */
.mobile-cards-container {
    display: none;
    padding: 20px;
    flex-direction: column;
    gap: 16px;
}

.mobile-card {
    background: #FFFFFF;
    border-radius: 12px;
    padding: 20px;
    border: 1px solid #E2E8F0;
    box-shadow: 0 1px 3px rgba(0,0,0,0.02);
}

.card-header-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #F1F5F9;
    padding-bottom: 12px;
    margin-bottom: 14px;
}

.card-title-main {
    font-weight: 600;
    color: #0F172A;
    font-size: 15px;
}

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

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

.detail-row .label { color: #64748B; }
.detail-row .value { color: #1E293B; font-weight: 500; }

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

.no-data {
    text-align: center;
    padding: 50px;
    color: #64748B;
    font-size: 15px;
}

.sidebar-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(15, 23, 42, 0.3);
    backdrop-filter: blur(4px);
    z-index: 998;
}

@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) {
    .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 20px; height: 65px; }
    .search-container { width: 160px; }
    .page-container { padding: 15px; }
    .form-banner { padding: 20px; flex-direction: column; gap: 16px; align-items: flex-start; }
    .btn-add { width: 100%; justify-content: center; }
    
    .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 quotations...">
                </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-lines"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Sales Estimates / Quotations</h2>
                            <p>Draft structural material references, configure pending project cost sheets, and confirm ledger pipelines</p>
                        </div>
                    </div>
                    <a href="quote_add.php" class="btn-add">
                        <i class="fa-solid fa-plus"></i> Create New Quote
                    </a>
                </div>

                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th style="width: 12%;">Quote No.</th>
                                <th style="width: 14%;">Date Issued</th>
                                <th style="width: 14%;">Valid Till</th>
                                <th style="width: 26%;">Customer Name</th>
                                <th style="width: 14%;">Amount</th>
                                <th style="width: 10%;">Status</th>
                                <th style="width: 10%;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if(count($quotes) > 0) {
                                foreach($quotes as $row) {
                                    $valid_date = date('d M Y', strtotime($row['valid_until']));
                                    $issue_date = date('d M Y', strtotime($row['date']));
                                    
                                    $quote_view_link = "quote_view.php?id=" . $row['id'];
                                    $delete_link = "quote_list.php?action=delete&id=" . $row['id'];
                                    $confirm_link = "quote_list.php?action=confirm&id=" . $row['id'];
                                    
                                    // Null safe operator setup to avoid deprecation warning
                                    $customer_name_clean = htmlspecialchars($row['customer_name'] ?? '');
                                    
                                    echo "<tr>
                                        <td><span style='font-weight: 600; color: #0F172A;'>#QT-00{$row['id']}</span></td>
                                        <td style='color: #64748B;'>{$issue_date}</td>
                                        <td><span style='color:#EF4444; font-weight:500;'>{$valid_date}</span></td>
                                        <td><span style='color: #0F172A; font-weight: 500;'>" . (!empty($customer_name_clean) ? $customer_name_clean : "Unknown Customer") . "</span></td>
                                        <td style='font-weight:600; color:#0F172A;'>" . number_format($row['amount'], 0) . " PKR</td>
                                        <td><span class='status-badge status-{$row['status']}'>{$row['status']}</span></td>
                                        <td>
                                            <div class='actions-group'>
                                                <a href='{$quote_view_link}' class='btn-action btn-view' title='View Quotation'><i class='fa-solid fa-eye'></i></a>";
                                                
                                                if($row['status'] === 'Pending') {
                                                    echo "<a href='{$confirm_link}' class='btn-action btn-confirm' title='Confirm & Convert' onclick='return confirm(\"Convert this estimate into an official invoice?\")'><i class='fa-solid fa-check'></i></a>";
                                                } else {
                                                    echo "<span class='converted-badge' title='Converted to official invoice'><i class='fa-solid fa-file-circle-check'></i></span>";
                                                }
                                                
                                                echo "
                                                <button onclick='triggerRowFile(${row['id']})' class='btn-action btn-attach' title='Attach Document'><i class='fa-solid fa-paperclip'></i></button>
                                                
                                                <a href='{$delete_link}' class='btn-action btn-delete' title='Delete Reference' onclick='return confirm(\"Are you sure you want to permanently delete this quotation reference record?\")'><i class='fa-solid fa-trash-can'></i></a>
                                            </div>
                                        </td>
                                    </tr>";
                                }
                            } else {
                                echo "<tr><td colspan='7' class='no-data'>⚠️ No Quotations Found.</td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>

                <div class="mobile-cards-container">
                    <?php 
                    if(count($quotes) > 0) {
                        foreach($quotes as $row) {
                            $valid_date = date('d M Y', strtotime($row['valid_until']));
                            $issue_date = date('d M Y', strtotime($row['date']));
                            
                            $quote_view_link = "quote_view.php?id=" . $row['id'];
                            $delete_link = "quote_list.php?action=delete&id=" . $row['id'];
                            $confirm_link = "quote_list.php?action=confirm&id=" . $row['id'];
                            
                            $mobile_customer_name = htmlspecialchars($row['customer_name'] ?? '');
                            ?>
                            <div class="mobile-card">
                                <div class="card-header-flex">
                                    <span class="card-title-main"><?php echo !empty($mobile_customer_name) ? $mobile_customer_name : "Unknown Customer"; ?></span>
                                    <span class="status-badge status-<?php echo $row['status']; ?>"><?php echo $row['status']; ?></span>
                                </div>
                                <div class="card-body-details">
                                    <div class="detail-row">
                                        <span class="label">Quote No:</span>
                                        <span class="value" style="color: #0F172A; font-weight:600;">#QT-00<?php echo $row['id']; ?></span>
                                    </div>
                                    <div class="detail-row">
                                        <span class="label">Issued:</span>
                                        <span class="value"><?php echo $issue_date; ?></span>
                                    </div>
                                    <div class="detail-row">
                                        <span class="label">Valid Till:</span>
                                        <span class="value" style="color:#EF4444; font-weight:500;"><?php echo $valid_date; ?></span>
                                    </div>
                                    <div class="detail-row" style="margin-top: 6px; border-top: 1px solid #F1F5F9; padding-top: 6px;">
                                        <span class="label" style="font-weight: 500;">Amount:</span>
                                        <span style="font-weight:700; color:#0F172A;"><?php echo number_format($row['amount'], 0); ?> PKR</span>
                                    </div>
                                </div>
                                <div class="card-actions-wrapper">
                                    <div class="actions-group">
                                        <a href="<?php echo $quote_view_link; ?>" class="btn-action btn-view"><i class="fa-solid fa-eye"></i></a>
                                        <?php if($row['status'] === 'Pending'): ?>
                                            <a href="<?php echo $confirm_link; ?>" class="btn-action btn-confirm" onclick="return confirm('Convert this estimate into an official invoice?')"><i class="fa-solid fa-check"></i></a>
                                        <?php else: ?>
                                            <span class="converted-badge"><i class="fa-solid fa-file-circle-check"></i></span>
                                        <?php endif; ?>
                                        <button onclick="triggerRowFile(<?php echo $row['id']; ?>)" class="btn-action btn-attach"><i class="fa-solid fa-paperclip"></i></button>
                                        <a href="<?php echo $delete_link; ?>" class="btn-action btn-delete" onclick="return confirm('Are you sure you want to permanently delete this quotation reference record?')"><i class="fa-solid fa-trash-can"></i></a>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                    } else {
                        echo '<div class="no-data">⚠️ No Quotations Found.</div>';
                    }
                    ?>
                </div>

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

<input type="file" id="globalRowFileInput" style="display:none;" multiple onchange="rowFileProcessed()">

<script>
let activeRowQuoteId = null;

function triggerRowFile(quoteId) {
    activeRowQuoteId = quoteId;
    document.getElementById('globalRowFileInput').click();
}

function rowFileProcessed() {
    let files = document.getElementById('globalRowFileInput').files;
    if(files.length > 0 && activeRowQuoteId !== null) {
        alert(files.length + " document(s) uploaded successfully for Quotation #QT-00" + activeRowQuoteId);
    }
}

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>