<?php
/**
 * Create New Quotation - Fixed Version
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

// REMOVE THIS LINE SINCE IT'S NOW IN DB_FUNCTIONS.PHP
// session_start();

// Define base path
define('BASE_PATH', dirname(__DIR__));

// Load database functions
require_once dirname(__DIR__) . '/config/db_functions.php';

// Require authentication (simplified for now)
if (function_exists('require_auth')) {
    require_auth();
}


$page_title = 'Create Quotation';
$current_user = function_exists('current_user') ? current_user() : ['user_id' => 1, 'username' => 'admin'];

// Handle form submission
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Begin transaction if function exists
        if (function_exists('db_begin_transaction')) {
            db_begin_transaction();
        }
        
        // Generate quotation number
        $quotation_number = function_exists('generate_quotation_number') ? 
                            generate_quotation_number() : 
                            'Q-' . date('Ymd') . '-' . rand(1000, 9999);
        
        // Insert quotation header
        $quotation_data = [
            'quotation_number' => $quotation_number,
            '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'] ?? date('Y-m-d'),
            'valid_until' => $_POST['valid_until'] ?? date('Y-m-d', strtotime('+30 days')),
            'subtotal' => $_POST['subtotal'] ?? 0,
            'vat_amount' => $_POST['vat_amount'] ?? 0,
            'vat_rate' => 18,
            'total_amount' => $_POST['total_amount'] ?? 0,
            'notes' => $_POST['notes'] ?? '',
            'status' => 'draft',
            'created_by' => $current_user['user_id'] ?? 1
        ];
        
        // Insert using db_insert if available
        if (function_exists('db_insert')) {
            $quotation_id = db_insert('quotations', $quotation_data);
        } else {
            // Fallback direct insert
            $connection = get_db_connection();
            $sql = "INSERT INTO quotations (quotation_number, customer_name, customer_address_line1, customer_address_line2, customer_email, customer_phone, issue_date, valid_until, subtotal, vat_amount, vat_rate, total_amount, notes, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = mysqli_prepare($connection, $sql);
            mysqli_stmt_bind_param($stmt, 'ssssssssdddsssi', 
                $quotation_data['quotation_number'],
                $quotation_data['customer_name'],
                $quotation_data['customer_address_line1'],
                $quotation_data['customer_address_line2'],
                $quotation_data['customer_email'],
                $quotation_data['customer_phone'],
                $quotation_data['issue_date'],
                $quotation_data['valid_until'],
                $quotation_data['subtotal'],
                $quotation_data['vat_amount'],
                $quotation_data['vat_rate'],
                $quotation_data['total_amount'],
                $quotation_data['notes'],
                $quotation_data['status'],
                $quotation_data['created_by']
            );
            
            mysqli_stmt_execute($stmt);
            $quotation_id = mysqli_insert_id($connection);
            mysqli_stmt_close($stmt);
        }
        
        if (!$quotation_id) {
            throw new Exception("Failed to create quotation");
        }
        
        // Insert quotation 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'] ?? 1,
                    'unit_price' => $item['unit_price'] ?? 0,
                    'discount_percent' => $item['discount_percent'] ?? 0,
                    'discount_amount' => $item['discount_amount'] ?? 0,
                    'subtotal' => $item['subtotal'] ?? 0,
                    'vat_amount' => $item['vat_amount'] ?? 0,
                    'total' => ($item['subtotal'] ?? 0) + ($item['vat_amount'] ?? 0)
                ];
                
                if (function_exists('db_insert')) {
                    db_insert('quotation_items', $item_data);
                } else {
                    // Fallback direct insert
                    $connection = get_db_connection();
                    $sql = "INSERT INTO quotation_items (quotation_id, description, quantity, unit_price, discount_percent, discount_amount, subtotal, vat_amount, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    
                    $stmt = mysqli_prepare($connection, $sql);
                    mysqli_stmt_bind_param($stmt, 'isidddddd', 
                        $item_data['quotation_id'],
                        $item_data['description'],
                        $item_data['quantity'],
                        $item_data['unit_price'],
                        $item_data['discount_percent'],
                        $item_data['discount_amount'],
                        $item_data['subtotal'],
                        $item_data['vat_amount'],
                        $item_data['total']
                    );
                    
                    mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);
                }
            }
        }
        
        // Commit transaction if function exists
        if (function_exists('db_commit')) {
            db_commit();
        }
        
        // Log activity if function exists
        if (function_exists('log_activity')) {
            log_activity($current_user['user_id'], 'create', 'quotation', $quotation_id, "Created quotation {$quotation_number}");
        }
        
        // Set success message in session
        $_SESSION['success'] = "Quotation created successfully";
        
        // Redirect to view page
        header("Location: view.php?id=" . $quotation_id);
        exit;
        
    } catch (Exception $e) {
        // Rollback if function exists
        if (function_exists('db_rollback')) {
            db_rollback();
        }
        $error = "Error creating quotation: " . $e->getMessage();
    }
}

// Default dates
$today = date('Y-m-d');
$valid_until = date('Y-m-d', strtotime('+30 days'));

// Include header
$header_path = dirname(__DIR__) . '/views/partials/header.php';
if (file_exists($header_path)) {
    include $header_path;
} else {
    // Simple header if not found
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Create Quotation</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    <body>
        <div class="container-fluid mt-4">
    <?php
}
?>

<!-- Display messages -->
<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="row mb-4">
    <div class="col-md-12">
        <h2><i class="fas fa-file-invoice"></i> Create New Quotation</h2>
        <hr>
    </div>
</div>

<form method="POST" id="quotationForm" onsubmit="return validateForm()">
    <!-- Company Info & Quote Details -->
    <div class="row">
        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-building"></i> Company Information</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Company Name</label>
                        <input type="text" class="form-control" value="Ruhondo Beach Resort" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Company Address</label>
                        <input type="text" class="form-control mb-2" value="Lake Ruhondo, Musanze" readonly>
                        <input type="text" class="form-control" value="Northern Province, Rwanda" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">TIN Number</label>
                        <input type="text" class="form-control" value="1234578364" readonly>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-hashtag"></i> Quote Information</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Quote Number</label>
                        <input type="text" class="form-control" value="<?php echo function_exists('generate_quotation_number') ? generate_quotation_number() : 'Q-' . date('Ymd') . '-0001'; ?>" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Issue Date *</label>
                        <input type="date" class="form-control" name="issue_date" value="<?php echo $today; ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Valid Through *</label>
                        <input type="date" class="form-control" name="valid_until" value="<?php echo $valid_until; ?>" required>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Customer Information -->
    <div class="card mb-4">
        <div class="card-header bg-info text-white">
            <h5 class="mb-0"><i class="fas fa-user"></i> Customer Information</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Customer Full Name *</label>
                        <input type="text" class="form-control" name="customer_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Address Line 1</label>
                        <input type="text" class="form-control" name="customer_address_line1">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Address Line 2</label>
                        <input type="text" class="form-control" name="customer_address_line2">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="customer_email">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Phone</label>
                        <input type="tel" class="form-control" name="customer_phone">
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quotation Items -->
    <div class="card mb-4">
        <div class="card-header bg-warning">
            <h5 class="mb-0"><i class="fas fa-list"></i> Quotation Items</h5>
            <div class="float-end">
                <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 mb-0" id="itemsTable">
                    <thead class="table-secondary">
                        <tr>
                            <th>QTY</th>
                            <th>DESCRIPTION</th>
                            <th>UNIT PRICE (RWF)</th>
                            <th>DISCOUNT %</th>
                            <th>SUBTOTAL (RWF)</th>
                            <th>VAT (18%) (RWF)</th>
                            <th>ACTION</th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">
                        <tr class="item-row">
                            <td>
                                <input type="number" class="form-control quantity" name="items[0][quantity]" value="5" min="1" step="1" onchange="calculateRow(this)">
                            </td>
                            <td>
                                <input type="text" class="form-control description" name="items[0][description]" value="Hotel Services - Deluxe Room" required>
                            </td>
                            <td>
                                <input type="number" class="form-control unit-price" name="items[0][unit_price]" value="4500.00" min="0" step="100" onchange="calculateRow(this)">
                            </td>
                            <td>
                                <input type="number" class="form-control discount-percent" name="items[0][discount_percent]" value="0" min="0" max="100" step="1" onchange="calculateRow(this)">
                            </td>
                            <td>
                                <input type="number" class="form-control subtotal" name="items[0][subtotal]" value="22500.00" readonly>
                            </td>
                            <td>
                                <input type="number" class="form-control vat-amount" name="items[0][vat_amount]" value="3375.00" 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>
                        <tr class="item-row discount-row">
                            <td>
                                <input type="number" class="form-control quantity" name="items[1][quantity]" value="5" min="1" step="1" onchange="calculateRow(this)">
                            </td>
                            <td>
                                <input type="text" class="form-control description" name="items[1][description]" value="Hotel Services (Discount 10%)">
                            </td>
                            <td>
                                <input type="number" class="form-control unit-price" name="items[1][unit_price]" value="-450.00" min="-999999" step="1" onchange="calculateRow(this)">
                            </td>
                            <td>
                                <input type="number" class="form-control discount-percent" name="items[1][discount_percent]" value="0" readonly>
                            </td>
                            <td>
                                <input type="number" class="form-control subtotal" name="items[1][subtotal]" value="-2250.00" readonly>
                            </td>
                            <td>
                                <input type="number" class="form-control vat-amount" name="items[1][vat_amount]" value="-337.50" 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>
                    </tbody>
                    <tfoot class="table-light">
                        <tr>
                            <td colspan="4" class="text-end"><strong>Subtotal:</strong></td>
                            <td>
                                <input type="number" class="form-control" id="totalSubtotal" name="subtotal" value="20250.00" readonly>
                            </td>
                            <td colspan="2"></td>
                        </tr>
                        <tr>
                            <td colspan="4" class="text-end"><strong>VAT (18%):</strong></td>
                            <td>
                                <input type="number" class="form-control" id="totalVat" name="vat_amount" value="3037.50" readonly>
                            </td>
                            <td colspan="2"></td>
                        </tr>
                        <tr>
                            <td colspan="4" class="text-end"><strong>Total:</strong></td>
                            <td>
                                <input type="number" class="form-control" id="grandTotal" name="total_amount" value="23287.50" readonly>
                            </td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    <!-- Notes -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="mb-3">
                <label class="form-label">Notes / Terms & Conditions</label>
                <textarea class="form-control" name="notes" rows="3" placeholder="Enter any additional notes, terms, or conditions..."></textarea>
            </div>
        </div>
        <div class="card-footer">
            <button type="submit" class="btn btn-success">
                <i class="fas fa-save"></i> Save Quotation
            </button>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-times"></i> Cancel
            </a>
        </div>
    </div>
</form>

<script>
let itemIndex = 2; // Start from 2 since we have 2 default rows

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
        let discountInput = row.querySelector('.discount-amount');
        if (!discountInput) {
            discountInput = document.createElement('input');
            discountInput.type = 'hidden';
            discountInput.className = 'discount-amount';
            discountInput.name = `items[${itemIndex-1}][discount_amount]`;
            row.appendChild(discountInput);
        }
        discountInput.value = discountAmount.toFixed(2);
    }
    
    // Calculate VAT (18%)
    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 validateForm() {
    const customerName = document.querySelector('[name="customer_name"]').value;
    if (!customerName.trim()) {
        alert('Please enter customer name');
        return false;
    }
    
    const items = document.querySelectorAll('.item-row');
    let hasValidItem = false;
    
    items.forEach(row => {
        const description = row.querySelector('.description').value;
        const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
        const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
        
        if (description.trim() && quantity > 0 && unitPrice !== 0) {
            hasValidItem = true;
        }
    });
    
    if (!hasValidItem) {
        alert('Please add at least one valid item');
        return false;
    }
    
    return true;
}

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

<style>
.card {
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    border: none;
    margin-bottom: 20px;
}
.card-header {
    background-color: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
    font-weight: 600;
}
.table th {
    background-color: #e9ecef;
}
.form-control:read-only {
    background-color: #e9ecef;
}
</style>

<?php
// Include footer
$footer_path = dirname(__DIR__) . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    include $footer_path;
} else {
    echo '</div></body></html>';
}
?>