<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$request_id = $_GET['request_id'] ?? '';

if (empty($request_id)) {
    header('Location: list_maintenance.php');
    exit();
}

// Get maintenance request details
$sql_request = "SELECT mr.*, v.company_name, v.id as vendor_id
                FROM maintenance_requests mr
                JOIN vendors v ON mr.assigned_vendor_id = v.id
                WHERE mr.request_id = ?";

$stmt_request = $conn->prepare($sql_request);
$stmt_request->bind_param("i", $request_id);
$stmt_request->execute();
$result_request = $stmt_request->get_result();
$request = $result_request->fetch_assoc();

if (!$request) {
    header('Location: list_maintenance.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $invoice_number = 'VINV-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    $amount = $_POST['amount'] ?? $request['final_cost'];
    $description = $_POST['description'] ?? 'Maintenance work completed';
    $due_date = $_POST['due_date'] ?? date('Y-m-d', strtotime('+30 days'));
    
    // Create vendor invoice
    $sql = "INSERT INTO vendor_invoices (vendor_id, maintenance_request_id, invoice_number, 
                                         amount, description, due_date, status, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iisds", $request['vendor_id'], $request_id, $invoice_number, 
                     $amount, $description, $due_date);
    
    if ($stmt->execute()) {
        // Update maintenance request final cost if not set
        if (!$request['final_cost']) {
            $sql_update = "UPDATE maintenance_requests SET final_cost = ? WHERE request_id = ?";
            $stmt_update = $conn->prepare($sql_update);
            $stmt_update->bind_param("di", $amount, $request_id);
            $stmt_update->execute();
        }
        
        $_SESSION['success_message'] = "Vendor invoice created successfully!";
        header('Location: list_maintenance.php');
        exit();
    } else {
        $error_message = "Error: " . $conn->error;
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Vendor Invoice')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Maintenance', 'title' => 'Create Vendor Invoice')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="maintenance_request_details.php?id=<?php echo $request_id; ?>" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i>Back to Request
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Create Invoice for <?php echo htmlspecialchars($request['company_name']); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info mb-3">
                                        <strong>Request:</strong> <?php echo htmlspecialchars($request['ticket_number'] ?? $request['request_code']); ?>
                                        <br><strong>Category:</strong> <?php echo htmlspecialchars($request['category']); ?>
                                    </div>

                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Amount (KES) <span class="text-danger">*</span></label>
                                            <input type="number" class="form-control" name="amount" 
                                                   value="<?php echo $request['final_cost'] ?? ''; ?>" 
                                                   step="0.01" required>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="description" rows="3" required>Maintenance work completed</textarea>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Due Date <span class="text-danger">*</span></label>
                                            <input type="date" class="form-control" name="due_date" 
                                                   value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                        </div>
                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-file-add-line align-bottom me-1"></i>Create Invoice
                                            </button>
                                            <a href="maintenance_request_details.php?id=<?php echo $request_id; ?>" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i>Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
