<?php
/**
 * Edit Quotation
 */

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

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

// Check permission
if (!has_permission('quotations.edit')) {
    $_SESSION['error'] = "You don't have permission to edit quotations";
    header("Location: index.php");
    exit;
}

$page_title = 'Edit Quotation';
$current_user = function_exists('current_user') ? current_user() : null;

// Get quotation ID from URL
$quotation_id = $_GET['id'] ?? 0;

// Fetch quotation details
$quotation = db_fetch_one("
    SELECT q.*, u.username as created_by_name
    FROM quotations q
    LEFT JOIN users u ON q.created_by = u.user_id
    WHERE q.quotation_id = ?
", [$quotation_id]);

if (!$quotation) {
    $_SESSION['error'] = "Quotation not found";
    header("Location: index.php");
    exit;
}

// Fetch quotation items
$items = db_fetch_all("
    SELECT * FROM quotation_items 
    WHERE quotation_id = ?
    ORDER BY item_id
", [$quotation_id]) ?: [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        db_begin_transaction();
        
        // Update quotation header
        $quotation_data = [
            'customer_name' => $_POST['customer_name'],
            'customer_address_line1' => $_POST['customer_address_line1'],
            'customer_address_line2' => $_POST['customer_address_line2'],
            'customer_email' => $_POST['customer_email'],
            'customer_phone' => $_POST['customer_phone'],
            'issue_date' => $_POST['issue_date'],
            'valid_until' => $_POST['valid_until'],
            'subtotal' => $_POST['subtotal'],
            'vat_amount' => $_POST['vat_amount'],
            'vat_rate' => 15,
            'total_amount' => $_POST['total_amount'],
            'notes' => $_POST['notes'],
            'status' => $_POST['status'] ?? $quotation['status']
        ];
        
        db_update('quotations', $quotation_data, 'quotation_id = ?', [$quotation_id]);
        
        // Delete existing items
        db_query("DELETE FROM quotation_items WHERE quotation_id = ?", [$quotation_id]);
        
        // Insert updated items
        if (isset($_POST['items']) && is_array($_POST['items'])) {
            foreach ($_POST['items'] as $item) {
                if (empty($item['description'])) continue;
                
                $item_data = [
                    'quotation_id' => $quotation_id,
                    'description' => $item['description'],
                    'quantity' => $item['quantity'],
                    'unit_price' => $item['unit_price'],
                    'discount_percent' => $item['discount_percent'] ?? 0,
                    'discount_amount' => $item['discount_amount'] ?? 0,
                    'subtotal' => $item['subtotal'],
                    'vat_amount' => $item['vat_amount'],
                    'total' => $item['total'] ?? ($item['subtotal'] + $item['vat_amount'])
                ];
                db_insert('quotation_items', $item_data);
            }
        }
        
        db_commit();
        
        // Log activity
        log_activity($current_user['user_id'], 'edit', 'quotation', $quotation_id, "Edited quotation {$quotation['quotation_number']}");
        
        $_SESSION['success'] = "Quotation updated successfully";
        header("Location: view.php?id=" . $quotation_id);
        exit;
        
    } catch (Exception $e) {
        db_rollback();
        $error = "Error updating quotation: " . $e->getMessage();
    }
}

// Generate new quotation number function (if needed for reference)
function generateQuotationNumber() {
    $year = date('Y');
    $month = date('m');
    $prefix = "Q-{$year}{$month}";
    
    $last = db_fetch_value("
        SELECT quotation_number FROM quotations 
        WHERE quotation_number LIKE ? 
        ORDER BY quotation_id DESC LIMIT 1
    ", [$prefix . '%']);
    
    if ($last) {
        $lastNum = intval(substr($last, -4));
        $newNum = $lastNum + 1;
    } else {
        $newNum = 1;
    }
    
    return $prefix . str_pad($newNum, 4, '0', STR_PAD_LEFT);
}

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

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Edit Quotation: <?php echo htmlspecialchars($quotation['quotation_number']); ?></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"><a href="index.php">Quotations</a></li>
                        <li class="breadcrumb-item"><a href="view.php?id=<?php echo $quotation_id; ?>">View</a></li>
                        <li class="breadcrumb-item active">Edit</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <?php if (isset($error)): ?>
                <div class="alert alert-danger"><?php echo $error; ?></div>
            <?php endif; ?>

            <!-- Status Bar -->
            <div class="row mb-3">
                <div class="col-12">
                    <div class="card card-<?php 
                        echo match($quotation['status']) {
                            'draft' => 'secondary',
                            'sent' => 'info',
                            'accepted' => 'success',
                            'expired' => 'warning',
                            'cancelled' => 'danger',
                            default => 'secondary'
                        };
                    ?>">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-info-circle"></i>
                                Current Status: <strong><?php echo ucfirst($quotation['status']); ?></strong>
                            </h3>
                            <div class="card-tools">
                                <a href="view.php?id=<?php echo $quotation_id; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-eye"></i> View Mode
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <form method="POST" id="quotationForm">
                <!-- Company Info & Quote Details -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h3 class="card-title">Company Information</h3>
                            </div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label>Company Name</label>
                                    <input type="text" class="form-control" value="Ruhondo Beach Resort" readonly>
                                </div>
                                <div class="form-group">
                                    <label>Company Address</label>
                                    <input type="text" class="form-control" value="Lake Ruhondo, Musanze" readonly>
                                    <input type="text" class="form-control mt-2" value="Northern Province, Rwanda" readonly>
                                </div>
                                <div class="form-group">
                                    <label>VAT Number</label>
                                    <input type="text" class="form-control" value="VAT0012345" readonly>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h3 class="card-title">Quote Information</h3>
                            </div>
                            <div class="card-body">
                                <div class="form-group">
                                    <label>Quote Number</label>
                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($quotation['quotation_number']); ?>" readonly>
                                </div>
                                <div class="form-group">
                                    <label>Issue Date *</label>
                                    <input type="date" class="form-control" name="issue_date" value="<?php echo $quotation['issue_date']; ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>Valid Through *</label>
                                    <input type="date" class="form-control" name="valid_until" value="<?php echo $quotation['valid_until']; ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>Status</label>
                                    <select class="form-control" name="status">
                                        <option value="draft" <?php echo $quotation['status'] == 'draft' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="sent" <?php echo $quotation['status'] == 'sent' ? 'selected' : ''; ?>>Sent</option>
                                        <option value="accepted" <?php echo $quotation['status'] == 'accepted' ? 'selected' : ''; ?>>Accepted</option>
                                        <option value="expired" <?php echo $quotation['status'] == 'expired' ? 'selected' : ''; ?>>Expired</option>
                                        <option value="cancelled" <?php echo $quotation['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Customer Information -->
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h3 class="card-title">Receiver / Customer Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Customer Full Name *</label>
                                    <input type="text" class="form-control" name="customer_name" value="<?php echo htmlspecialchars($quotation['customer_name']); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label>Address Line 1</label>
                                    <input type="text" class="form-control" name="customer_address_line1" value="<?php echo htmlspecialchars($quotation['customer_address_line1'] ?? ''); ?>">
                                </div>
                                <div class="form-group">
                                    <label>Address Line 2</label>
                                    <input type="text" class="form-control" name="customer_address_line2" value="<?php echo htmlspecialchars($quotation['customer_address_line2'] ?? ''); ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Email</label>
                                    <input type="email" class="form-control" name="customer_email" value="<?php echo htmlspecialchars($quotation['customer_email'] ?? ''); ?>">
                                </div>
                                <div class="form-group">
                                    <label>Phone</label>
                                    <input type="tel" class="form-control" name="customer_phone" value="<?php echo htmlspecialchars($quotation['customer_phone'] ?? ''); ?>">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quotation Items Table -->
                <div class="card">
                    <div class="card-header bg-warning">
                        <h3 class="card-title">Quotation Items</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" onclick="addItem()">
                                <i class="fas fa-plus"></i> Add Item
                            </button>
                            <button type="button" class="btn btn-sm btn-info" onclick="addDiscountRow()">
                                <i class="fas fa-percent"></i> Add Discount
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="itemsTable">
                                <thead class="bg-secondary text-white">
                                    <tr>
                                        <th>QTY</th>
                                        <th>DESCRIPTION</th>
                                        <th>UNIT PRICE</th>
                                        <th>DISCOUNT %</th>
                                        <th>SUBTOTAL</th>
                                        <th>VAT (15%)</th>
                                        <th>ACTION</th>
                                    </tr>
                                </thead>
                                <tbody id="itemsBody">
                                    <?php 
                                    $item_index = 0;
                                    foreach ($items as $item): 
                                    ?>
                                    <tr class="item-row">
                                        <td>
                                            <input type="number" class="form-control quantity" name="items[<?php echo $item_index; ?>][quantity]" value="<?php echo $item['quantity']; ?>" min="1" step="1" onchange="calculateRow(this)">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control description" name="items[<?php echo $item_index; ?>][description]" value="<?php echo htmlspecialchars($item['description']); ?>" required>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control unit-price" name="items[<?php echo $item_index; ?>][unit_price]" value="<?php echo $item['unit_price']; ?>" min="0" step="100" onchange="calculateRow(this)">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control discount-percent" name="items[<?php echo $item_index; ?>][discount_percent]" value="<?php echo $item['discount_percent']; ?>" min="0" max="100" step="1" onchange="calculateRow(this)">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control subtotal" name="items[<?php echo $item_index; ?>][subtotal]" value="<?php echo $item['subtotal']; ?>" readonly>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control vat-amount" name="items[<?php echo $item_index; ?>][vat_amount]" value="<?php echo $item['vat_amount']; ?>" readonly>
                                        </td>
                                        <td class="text-center">
                                            <button type="button" class="btn btn-sm btn-danger" onclick="removeItem(this)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php 
                                    $item_index++;
                                    endforeach; 
                                    ?>
                                </tbody>
                                <tfoot class="bg-light">
                                    <tr>
                                        <td colspan="4" class="text-right"><strong>Subtotal:</strong></td>
                                        <td>
                                            <input type="number" class="form-control" id="totalSubtotal" name="subtotal" value="<?php echo $quotation['subtotal']; ?>" readonly>
                                        </td>
                                        <td colspan="2"></td>
                                    </tr>
                                    <tr>
                                        <td colspan="4" class="text-right"><strong>VAT (15%):</strong></td>
                                        <td>
                                            <input type="number" class="form-control" id="totalVat" name="vat_amount" value="<?php echo $quotation['vat_amount']; ?>" readonly>
                                        </td>
                                        <td colspan="2"></td>
                                    </tr>
                                    <tr>
                                        <td colspan="4" class="text-right"><strong>Total:</strong></td>
                                        <td>
                                            <input type="number" class="form-control" id="grandTotal" name="total_amount" value="<?php echo $quotation['total_amount']; ?>" readonly>
                                        </td>
                                        <td colspan="2"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Notes -->
                <div class="card">
                    <div class="card-body">
                        <div class="form-group">
                            <label>Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Enter any additional notes or terms..."><?php echo htmlspecialchars($quotation['notes'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    <div class="card-footer">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save"></i> Update Quotation
                        </button>
                        <a href="view.php?id=<?php echo $quotation_id; ?>" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                        <?php if (has_permission('quotations.send') && $quotation['status'] == 'draft'): ?>
                        <button type="button" class="btn btn-info float-right" onclick="sendQuotation(<?php echo $quotation_id; ?>)">
                            <i class="fas fa-paper-plane"></i> Send to Customer
                        </button>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>
    </section>
</div>

<!-- Hidden form for sending quotation -->
<form id="sendForm" method="POST" action="send.php" style="display: none;">
    <input type="hidden" name="quotation_id" value="<?php echo $quotation_id; ?>">
    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
</form>

<script>
let itemIndex = <?php echo count($items); ?>;

function addItem() {
    const tbody = document.getElementById('itemsBody');
    const newRow = document.createElement('tr');
    newRow.className = 'item-row';
    newRow.innerHTML = `
        <td>
            <input type="number" class="form-control quantity" name="items[${itemIndex}][quantity]" value="1" min="1" step="1" onchange="calculateRow(this)">
        </td>
        <td>
            <input type="text" class="form-control description" name="items[${itemIndex}][description]" placeholder="Description" required>
        </td>
        <td>
            <input type="number" class="form-control unit-price" name="items[${itemIndex}][unit_price]" value="0" min="0" step="100" onchange="calculateRow(this)">
        </td>
        <td>
            <input type="number" class="form-control discount-percent" name="items[${itemIndex}][discount_percent]" value="0" min="0" max="100" step="1" onchange="calculateRow(this)">
        </td>
        <td>
            <input type="number" class="form-control subtotal" name="items[${itemIndex}][subtotal]" value="0" readonly>
        </td>
        <td>
            <input type="number" class="form-control vat-amount" name="items[${itemIndex}][vat_amount]" value="0" readonly>
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-danger" onclick="removeItem(this)">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    itemIndex++;
}

function addDiscountRow() {
    const tbody = document.getElementById('itemsBody');
    const newRow = document.createElement('tr');
    newRow.className = 'item-row discount-row';
    newRow.innerHTML = `
        <td>
            <input type="number" class="form-control quantity" name="items[${itemIndex}][quantity]" value="1" min="1" step="1" onchange="calculateRow(this)">
        </td>
        <td>
            <input type="text" class="form-control description" name="items[${itemIndex}][description]" value="Discount" placeholder="Discount Description">
        </td>
        <td>
            <input type="number" class="form-control unit-price" name="items[${itemIndex}][unit_price]" value="-0" min="-999999" step="100" onchange="calculateRow(this)">
        </td>
        <td>
            <input type="number" class="form-control discount-percent" name="items[${itemIndex}][discount_percent]" value="0" readonly>
        </td>
        <td>
            <input type="number" class="form-control subtotal" name="items[${itemIndex}][subtotal]" value="0" readonly>
        </td>
        <td>
            <input type="number" class="form-control vat-amount" name="items[${itemIndex}][vat_amount]" value="0" readonly>
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-danger" onclick="removeItem(this)">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    itemIndex++;
}

function removeItem(btn) {
    const row = btn.closest('tr');
    if (document.querySelectorAll('.item-row').length > 1) {
        row.remove();
        calculateTotals();
    } else {
        alert('You must keep at least one item');
    }
}

function calculateRow(element) {
    const row = element.closest('tr');
    const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
    const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
    const discountPercent = parseFloat(row.querySelector('.discount-percent').value) || 0;
    
    // Calculate subtotal (quantity * unit price)
    let subtotal = quantity * unitPrice;
    
    // Apply discount if any
    if (discountPercent > 0) {
        const discountAmount = subtotal * (discountPercent / 100);
        subtotal = subtotal - discountAmount;
        
        // Store discount amount
        if (!row.querySelector('.discount-amount')) {
            const discountInput = document.createElement('input');
            discountInput.type = 'hidden';
            discountInput.className = 'discount-amount';
            discountInput.name = row.querySelector('[name*="[discount_amount]"]')?.name || `items[${itemIndex-1}][discount_amount]`;
            discountInput.value = discountAmount.toFixed(2);
            row.appendChild(discountInput);
        } else {
            row.querySelector('.discount-amount').value = discountAmount.toFixed(2);
        }
    }
    
    // Calculate VAT (15%)
    const vatAmount = subtotal * 0.15;
    
    // Update fields
    row.querySelector('.subtotal').value = subtotal.toFixed(2);
    row.querySelector('.vat-amount').value = vatAmount.toFixed(2);
    
    calculateTotals();
}

function calculateTotals() {
    let totalSubtotal = 0;
    let totalVat = 0;
    
    document.querySelectorAll('.subtotal').forEach(input => {
        totalSubtotal += parseFloat(input.value) || 0;
    });
    
    document.querySelectorAll('.vat-amount').forEach(input => {
        totalVat += parseFloat(input.value) || 0;
    });
    
    const grandTotal = totalSubtotal + totalVat;
    
    document.getElementById('totalSubtotal').value = totalSubtotal.toFixed(2);
    document.getElementById('totalVat').value = totalVat.toFixed(2);
    document.getElementById('grandTotal').value = grandTotal.toFixed(2);
}

function sendQuotation(id) {
    if (confirm('Are you sure you want to send this quotation to the customer?')) {
        document.getElementById('sendForm').submit();
    }
}

// Initialize calculation for existing rows
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.quantity, .unit-price, .discount-percent').forEach(input => {
        calculateRow(input);
    });
});
</script>

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