<?php
require_once 'config/database.php';
require_once 'config/session.php';
require_once 'includes/header.php';

requireLogin();

$pageTitle = 'Quotation Management';
$action = $_GET['action'] ?? 'list';
$quotationId = $_GET['id'] ?? null;
$step = $_GET['step'] ?? 1;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $pdo = getConnection();
        
        if ($action == 'add') {
            if ($step == 1) {
                // Step 1: Customer selection
                $customerId = $_POST['customer_id'];
                if (empty($customerId)) {
                    throw new Exception('Please select a customer');
                }
                $_SESSION['quotation_customer_id'] = $customerId;
                header('Location: quotations.php?action=add&step=2');
                exit();
                
            } elseif ($step == 2) {
                // Step 2: Company details (can be skipped for now)
                header('Location: quotations.php?action=add&step=3');
                exit();
                
            } elseif ($step == 3) {
                // Step 3: Material selection and final submission
                $customerId = $_SESSION['quotation_customer_id'];
                $materials = $_POST['materials'] ?? [];
                $quantities = $_POST['quantities'] ?? [];
                $rates = $_POST['rates'] ?? [];
                $notes = trim($_POST['notes'] ?? '');
                
                if (empty($materials)) {
                    throw new Exception('Please add at least one material');
                }
                
                // Calculate totals
                $subtotal = 0;
                $materialData = [];
                
                foreach ($materials as $index => $materialId) {
                    $quantity = intval($quantities[$index]);
                    $rate = floatval($rates[$index]);
                    $total = $quantity * $rate;
                    
                    if ($quantity > 0 && $rate > 0) {
                        $materialData[] = [
                            'material_id' => $materialId,
                            'quantity' => $quantity,
                            'rate' => $rate,
                            'total' => $total
                        ];
                        $subtotal += $total;
                    }
                }
                
                if (empty($materialData)) {
                    throw new Exception('Please add valid materials with quantity and rate');
                }
                
                // Generate quotation number
                $quotationNumber = 'QTN-' . date('Y') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
                
                // Insert quotation
                $stmt = $pdo->prepare("INSERT INTO quotations (quotation_number, customer_id, issue_date, subtotal, grand_total, notes) VALUES (?, ?, CURDATE(), ?, ?, ?)");
                $stmt->execute([$quotationNumber, $customerId, $subtotal, $subtotal, $notes]);
                $quotationId = $pdo->lastInsertId();
                
                // Insert quotation items
                $stmt = $pdo->prepare("INSERT INTO quotation_items (quotation_id, material_id, quantity, rate, total) VALUES (?, ?, ?, ?, ?)");
                foreach ($materialData as $item) {
                    $stmt->execute([$quotationId, $item['material_id'], $item['quantity'], $item['rate'], $item['total']]);
                }
                
                // Clear session data
                unset($_SESSION['quotation_customer_id']);
                
                $_SESSION['success_message'] = 'Quotation created successfully!';
                header('Location: quotations.php');
                exit();
            }
        }
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Handle delete action
if ($action == 'delete' && $quotationId) {
    try {
        $pdo = getConnection();
        $pdo->beginTransaction();
        
        // Delete quotation items first
        $stmt = $pdo->prepare("DELETE FROM quotation_items WHERE quotation_id = ?");
        $stmt->execute([$quotationId]);
        
        // Delete quotation
        $stmt = $pdo->prepare("DELETE FROM quotations WHERE id = ?");
        $stmt->execute([$quotationId]);
        
        $pdo->commit();
        $_SESSION['success_message'] = 'Quotation deleted successfully!';
        header('Location: quotations.php');
        exit();
    } catch (Exception $e) {
        $pdo->rollback();
        $_SESSION['error_message'] = 'Error deleting quotation';
    }
}

// Get customers for dropdown
$customers = [];
try {
    $pdo = getConnection();
    $stmt = $pdo->query("SELECT * FROM customers ORDER BY name");
    $customers = $stmt->fetchAll();
} catch (Exception $e) {
    $customers = [];
}

// Get materials for selection
$materials = [];
try {
    $pdo = getConnection();
    $stmt = $pdo->query("SELECT * FROM materials ORDER BY name");
    $materials = $stmt->fetchAll();
} catch (Exception $e) {
    $materials = [];
}

// Get all quotations for listing
$quotations = [];
$search = $_GET['search'] ?? '';
try {
    $pdo = getConnection();
    if ($search) {
        $stmt = $pdo->prepare("
            SELECT q.*, c.name as customer_name 
            FROM quotations q 
            JOIN customers c ON q.customer_id = c.id 
            WHERE q.quotation_number LIKE ? OR c.name LIKE ?
            ORDER BY q.created_at DESC
        ");
        $searchTerm = "%$search%";
        $stmt->execute([$searchTerm, $searchTerm]);
    } else {
        $stmt = $pdo->query("
            SELECT q.*, c.name as customer_name 
            FROM quotations q 
            JOIN customers c ON q.customer_id = c.id 
            ORDER BY q.created_at DESC
        ");
    }
    $quotations = $stmt->fetchAll();
} catch (Exception $e) {
    $_SESSION['error_message'] = 'Error loading quotations';
}
?>

<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">
                    <i class="fas fa-file-alt"></i> Quotation Management
                </h1>
                <?php if ($action == 'list'): ?>
                    <a href="quotations.php?action=add" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add Quotation
                    </a>
                <?php else: ?>
                    <a href="quotations.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <?php if ($action == 'list'): ?>
        <!-- Quotation List -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="m-0 font-weight-bold text-primary">All Quotations</h6>
                            </div>
                            <div class="col-auto">
                                <form method="GET" class="d-flex">
                                    <input type="hidden" name="action" value="list">
                                    <input type="text" class="form-control me-2" name="search" 
                                           placeholder="Search quotations..." value="<?php echo htmlspecialchars($search); ?>">
                                    <button type="submit" class="btn btn-outline-primary">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (empty($quotations)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                <p class="text-muted">No quotations found.</p>
                                <a href="quotations.php?action=add" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Add First Quotation
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Quotation #</th>
                                            <th>Customer</th>
                                            <th>Issue Date</th>
                                            <th>Total Amount</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($quotations as $quotation): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($quotation['quotation_number']); ?></td>
                                            <td><?php echo htmlspecialchars($quotation['customer_name']); ?></td>
                                            <td><?php echo date('d M Y', strtotime($quotation['issue_date'])); ?></td>
                                            <td>₹<?php echo number_format($quotation['grand_total'], 2); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo $quotation['status'] == 'accepted' ? 'success' : ($quotation['status'] == 'rejected' ? 'danger' : 'warning'); ?>">
                                                    <?php echo ucfirst($quotation['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="view_quotation.php?id=<?php echo $quotation['id']; ?>" 
                                                   class="btn btn-sm btn-outline-info" target="_blank" title="View">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="pdf_quotation.php?id=<?php echo $quotation['id']; ?>" 
                                                   class="btn btn-sm btn-outline-success" target="_blank" title="Download PDF">
                                                    <i class="fas fa-download"></i>
                                                </a>
                                                <a href="quotations.php?action=delete&id=<?php echo $quotation['id']; ?>" 
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Are you sure you want to delete this quotation?')" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
    <?php elseif ($action == 'add'): ?>
        <!-- Add Quotation Multi-step Form -->
        <div class="row justify-content-center">
            <div class="col-md-10">
                <div class="card shadow">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-plus"></i> Add New Quotation
                        </h6>
                        <!-- Progress Steps -->
                        <div class="progress mt-3" style="height: 5px;">
                            <div class="progress-bar" role="progressbar" style="width: <?php echo ($step / 3) * 100; ?>%"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-2">
                            <small class="<?php echo $step >= 1 ? 'text-primary fw-bold' : 'text-muted'; ?>">Step 1: Customer</small>
                            <small class="<?php echo $step >= 2 ? 'text-primary fw-bold' : 'text-muted'; ?>">Step 2: Company Details</small>
                            <small class="<?php echo $step >= 3 ? 'text-primary fw-bold' : 'text-muted'; ?>">Step 3: Materials</small>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if ($step == 1): ?>
                            <!-- Step 1: Customer Selection -->
                            <form method="POST">
                                <div class="mb-4">
                                    <h5>Select Customer</h5>
                                    <p class="text-muted">Choose the customer for this quotation.</p>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="customer_id" class="form-label">Customer *</label>
                                    <select class="form-select" id="customer_id" name="customer_id" required>
                                        <option value="">Select a customer...</option>
                                        <?php foreach ($customers as $customer): ?>
                                        <option value="<?php echo $customer['id']; ?>">
                                            <?php echo htmlspecialchars($customer['name'] . ' - ' . $customer['contact_number']); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="d-flex justify-content-end">
                                    <a href="quotations.php" class="btn btn-secondary me-2">Cancel</a>
                                    <button type="submit" class="btn btn-primary">Next Step</button>
                                </div>
                            </form>
                            
                        <?php elseif ($step == 2): ?>
                            <!-- Step 2: Company Details -->
                            <form method="POST">
                                <div class="mb-4">
                                    <h5>Company Details</h5>
                                    <p class="text-muted">Review company information for the quotation.</p>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <img src="assets/img/logo.png" alt="The Sky Devlopers" width="150" height="150" class="img-fluid">
                                        
                                        <p><strong>Company Name:</strong> The Sky Devlopers</p>
                                        <p><strong>Address:</strong> FF-29 Shree Sidhheswar Harbours,waghodiya Road,NH-8 vadodara-390025, Vadodara, Gujarat 390011</p>
                                        <p><strong>Contact:</strong> +91 70163 25717</p>
                                        <p><strong>GST:</strong> NA</p>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>Customer Information</h6>
                                        <?php
                                        $selectedCustomer = null;
                                        if (isset($_SESSION['quotation_customer_id'])) {
                                            foreach ($customers as $customer) {
                                                if ($customer['id'] == $_SESSION['quotation_customer_id']) {
                                                    $selectedCustomer = $customer;
                                                    break;
                                                }
                                            }
                                        }
                                        ?>
                                        <?php if ($selectedCustomer): ?>
                                        <p><strong>Name:</strong> <?php echo htmlspecialchars($selectedCustomer['name']); ?></p>
                                        <p><strong>Contact:</strong> <?php echo htmlspecialchars($selectedCustomer['contact_number']); ?></p>
                                        <p><strong>Email:</strong> <?php echo htmlspecialchars($selectedCustomer['email']); ?></p>
                                        <p><strong>Address:</strong> <?php echo htmlspecialchars($selectedCustomer['address']); ?></p>
                                        <p><strong>GST:</strong> <?php echo htmlspecialchars($selectedCustomer['gst_number']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-end">
                                    <a href="quotations.php?action=add&step=1" class="btn btn-secondary me-2">Previous</a>
                                    <button type="submit" class="btn btn-primary">Next Step</button>
                                </div>
                            </form>
                            
                        <?php elseif ($step == 3): ?>
                            <!-- Step 3: Material Selection -->
                            <form method="POST" id="quotationForm">
                                <div class="mb-4">
                                    <h5>Add Materials</h5>
                                    <p class="text-muted">Select materials and quantities for this quotation.</p>
                                </div>
                                
                                <div id="materialsContainer">
                                    <div class="material-row row mb-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Material</label>
                                            <select class="form-select material-select" name="materials[]" required>
                                                <option value="">Select material...</option>
                                                <?php foreach ($materials as $material): ?>
                                                <option value="<?php echo $material['id']; ?>" data-price="<?php echo $material['unit_price']; ?>">
                                                    <?php echo htmlspecialchars($material['name'] . ' - ₹' . number_format($material['unit_price'], 2)); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Quantity</label>
                                            <input type="number" class="form-control quantity-input" name="quantities[]" min="1" value="1" required>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Rate (₹)</label>
                                            <input type="number" class="form-control rate-input" name="rates[]" step="0.01" min="0" required>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Total (₹)</label>
                                            <input type="text" class="form-control total-display" readonly>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <button type="button" class="btn btn-danger btn-sm w-100 remove-material">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <button type="button" class="btn btn-outline-primary" id="addMaterial">
                                        <i class="fas fa-plus"></i> Add Another Material
                                    </button>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="notes" class="form-label">Notes (Optional)</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Additional notes for this quotation..."></textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="d-flex justify-content-end">
                                            <a href="quotations.php?action=add&step=2" class="btn btn-secondary me-2">Previous</a>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="text-end">
                                            <h5>Subtotal: ₹<span id="subtotal">0.00</span></h5>
                                            <button type="submit" class="btn btn-success btn-lg">
                                                <i class="fas fa-save"></i> Create Quotation
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Material management
    const materialsContainer = document.getElementById('materialsContainer');
    const addMaterialBtn = document.getElementById('addMaterial');
    const subtotalSpan = document.getElementById('subtotal');
    
    // Add material row
    addMaterialBtn.addEventListener('click', function() {
        const newRow = materialsContainer.firstElementChild.cloneNode(true);
        newRow.querySelectorAll('input, select').forEach(input => {
            input.value = '';
            if (input.classList.contains('total-display')) {
                input.value = '0.00';
            }
        });
        materialsContainer.appendChild(newRow);
        attachMaterialEvents(newRow);
    });
    
    // Remove material row
    function attachMaterialEvents(row) {
        row.querySelector('.remove-material').addEventListener('click', function() {
            if (materialsContainer.children.length > 1) {
                row.remove();
                calculateSubtotal();
            }
        });
        
        row.querySelector('.material-select').addEventListener('change', function() {
            const price = this.options[this.selectedIndex].dataset.price;
            const rateInput = row.querySelector('.rate-input');
            if (price) {
                rateInput.value = price;
            }
            calculateRowTotal(row);
        });
        
        row.querySelector('.quantity-input').addEventListener('input', calculateRowTotal.bind(null, row));
        row.querySelector('.rate-input').addEventListener('input', calculateRowTotal.bind(null, row));
    }
    
    // Calculate row total
    function calculateRowTotal(row) {
        const quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
        const rate = parseFloat(row.querySelector('.rate-input').value) || 0;
        const total = quantity * rate;
        row.querySelector('.total-display').value = total.toFixed(2);
        calculateSubtotal();
    }
    
    // Calculate subtotal
    function calculateSubtotal() {
        let subtotal = 0;
        document.querySelectorAll('.total-display').forEach(input => {
            subtotal += parseFloat(input.value) || 0;
        });
        subtotalSpan.textContent = subtotal.toFixed(2);
    }
    
    // Attach events to initial row
    attachMaterialEvents(materialsContainer.firstElementChild);
});
</script>

<?php require_once 'includes/footer.php'; ?>
