<?php
/**
 * Quotation System - Main Listing Page
 */

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

require_once dirname(__DIR__) . '/config/init.php';
require_auth();

$page_title = 'Quotation Management';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    try {
        db_query("DELETE FROM quotations WHERE quotation_id = ?", [$_GET['delete']]);
        $success_message = "Quotation deleted successfully";
    } catch (Exception $e) {
        $error_message = "Error deleting quotation: " . $e->getMessage();
    }
}

// Get all quotations
$quotations = db_fetch_all("
    SELECT q.*, 
           DATEDIFF(q.valid_until, CURDATE()) as days_valid,
           CASE 
               WHEN q.status = 'accepted' THEN 'accepted'
               WHEN q.status = 'cancelled' THEN 'cancelled'
               WHEN q.valid_until < CURDATE() THEN 'expired'
               ELSE q.status 
           END as current_status
    FROM quotations q
    ORDER BY q.created_at DESC
") ?: [];

// Include header
include dirname(__DIR__) . '/views/partials/header.php';
?>

<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Quotation Management</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                        <li class="breadcrumb-item active">Quotations</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <?php if (isset($success_message)): ?>
                <div class="alert alert-success alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <?php echo $success_message; ?>
                </div>
            <?php endif; ?>
            
            <?php if (isset($error_message)): ?>
                <div class="alert alert-danger alert-dismissible">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    <?php echo $error_message; ?>
                </div>
            <?php endif; ?>

            <!-- Quick Actions -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus-circle"></i> Create New Quotation
                            </a>
                            <a href="search.php" class="btn btn-info">
                                <i class="fas fa-search"></i> Search Quotations
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quotations Table -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">All Quotations</h3>
                    <div class="card-tools">
                        <div class="input-group input-group-sm" style="width: 250px;">
                            <input type="text" name="table_search" class="form-control float-right" placeholder="Search" id="searchInput">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-default" onclick="searchTable()">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="card-body table-responsive p-0">
                    <table class="table table-hover text-nowrap" id="quotationsTable">
                        <thead>
                            <tr>
                                <th>Quote #</th>
                                <th>Customer</th>
                                <th>Issue Date</th>
                                <th>Valid Until</th>
                                <th>Total</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($quotations)): ?>
                                <tr>
                                    <td colspan="7" class="text-center py-4">
                                        <i class="fas fa-file-invoice fa-3x mb-3 text-muted"></i>
                                        <p class="text-muted">No quotations found. Create your first quotation!</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($quotations as $quote): 
                                    $status_class = match($quote['current_status'] ?? $quote['status']) {
                                        'draft' => 'badge-secondary',
                                        'sent' => 'badge-info',
                                        'accepted' => 'badge-success',
                                        'expired' => 'badge-warning',
                                        'cancelled' => 'badge-danger',
                                        default => 'badge-secondary'
                                    };
                                    
                                    $status_text = ucfirst($quote['current_status'] ?? $quote['status']);
                                ?>
                                <tr>
                                    <td>
                                        <a href="view.php?id=<?php echo $quote['quotation_id']; ?>">
                                            <strong><?php echo htmlspecialchars($quote['quotation_number']); ?></strong>
                                        </a>
                                    </td>
                                    <td><?php echo htmlspecialchars($quote['customer_name']); ?></td>
                                    <td><?php echo date('d M Y', strtotime($quote['issue_date'])); ?></td>
                                    <td>
                                        <?php echo date('d M Y', strtotime($quote['valid_until'])); ?>
                                        <?php if (isset($quote['days_valid']) && $quote['days_valid'] < 0): ?>
                                            <span class="badge badge-warning">Expired</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo format_currency($quote['total_amount']); ?></td>
                                    <td>
                                        <span class="badge <?php echo $status_class; ?>">
                                            <?php echo $status_text; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="view.php?id=<?php echo $quote['quotation_id']; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="edit.php?id=<?php echo $quote['quotation_id']; ?>" 
                                               class="btn btn-sm btn-primary" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="print.php?id=<?php echo $quote['quotation_id']; ?>" 
                                               class="btn btn-sm btn-secondary" title="Print" target="_blank">
                                                <i class="fas fa-print"></i>
                                            </a>
                                            <a href="pdf.php?id=<?php echo $quote['quotation_id']; ?>" 
                                               class="btn btn-sm btn-danger" title="Download PDF">
                                                <i class="fas fa-file-pdf"></i>
                                            </a>
                                            <a href="#" onclick="confirmDelete(<?php echo $quote['quotation_id']; ?>)" 
                                               class="btn btn-sm btn-danger" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
function searchTable() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("searchInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("quotationsTable");
    tr = table.getElementsByTagName("tr");
    
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        for (var j = 0; j < td.length; j++) {
            if (td[j]) {
                txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                    break;
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
}

function confirmDelete(id) {
    if (confirm('Are you sure you want to delete this quotation?')) {
        window.location.href = 'index.php?delete=' + id;
    }
}
</script>

<?php include dirname(__DIR__) . '/views/partials/footer.php'; ?>