<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

$allowed_roles = ['store manager', 'admin', 'project manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header("Location: ../login.php");
    exit();
}

$success = "";
$error = "";

// Generate Service Code
// function generateServiceCode(mysqli $conn): string {
//     $sql = "SELECT service_code FROM service_master ORDER BY id DESC LIMIT 1";
//     $res = $conn->query($sql);
//     $next = 1;
//     if ($res && $row = $res->fetch_assoc()) {
//         $next = (int)substr($row['service_code'], 4) + 1;
//     }
//     return sprintf("SVC-%03d", $next);
// }

// $generated_code = generateServiceCode($conn);

// Fetch Active Technicians for dropdown + search
$technicians = $conn->query("
    SELECT id, technician_code, full_name 
    FROM technician_master 
    WHERE status = 'Active' 
    ORDER BY full_name ASC
")->fetch_all(MYSQLI_ASSOC);

// ====================== FORM SUBMISSION ======================

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Service Request</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 1100px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 30px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(168,85,247,0.35), rgba(147,51,234,0.25));
            padding: 50px 40px;
            text-align: center;
        }
        .header h1 {
            font-size: clamp(28px, 5.5vw, 42px);
            font-weight: 700;
        }

        .form-area { padding: 45px 40px; }

        .section {
            background: rgba(255,255,255,0.07);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 30px;
        }

        label {
            display: block;
            margin-bottom: 9px;
            font-weight: 600;
            color: #e0e7ff;
        }
        .required { color: #f87171; }

        input, select, textarea {
            width: 100%;
            padding: 14px 18px;
            background: rgba(255,255,255,0.09);
            border: 1px solid rgba(255,255,255,0.25);
            border-radius: 16px;
            color: white;
            font-size: 16px;
        }
        input:focus, select:focus, textarea:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(168,85,247,0.25);
        }

        .product-row {
            position: relative;
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.18);
            border-radius: 18px;
            padding: 25px;
            margin-bottom: 25px;
        }
        .remove-product {
            position: absolute;
            top: 15px;
            right: 15px;
            background: rgba(239,68,68,0.3);
            color: #fda4af;
            border: none;
            width: 38px;
            height: 38px;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
        }
        .remove-product:hover {
            background: #ef4444;
            color: white;
            transform: rotate(90deg);
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
        }

        .add-row-btn, .submit-btn {
            width: 100%;
            padding: 18px;
            border-radius: 18px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            margin: 25px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }
        .add-row-btn {
            background: rgba(255,255,255,0.06);
            color: white;
            border: 2px dashed rgba(192,132,252,0.6);
        }
        .submit-btn {
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: white;
            border: none;
        }

        .message {
            padding: 16px 24px;
            border-radius: 16px;
            margin-bottom: 25px;
            font-weight: 600;
        }
        .success { background: rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }
        .error   { background: rgba(239,68,68,0.25); border:1px solid #f87171; color:#fca5a5; }

        @media (max-width: 768px) {
            .form-area { padding: 30px 20px; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="service_list.php" style="color:#c4b5fd; text-decoration:none; position:absolute; left:40px; top:45px;">
                ← Back to Services
            </a>
            <h1><i class="fas fa-wrench"></i> New Service Request</h1>
            <p style="margin-top:12px; opacity:0.9;">Create a new service job</p>
        </div>

        <div class="form-area">
            <?php if ($success): ?><div class="message success"><?= $success ?></div><?php endif; ?>
            <?php if ($error): ?><div class="message error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

            <form method="POST" id="serviceForm">

                <div class="section">
                    <div class="form-grid">
                        <div>
                            <label>Service Code <span class="required">*</span></label>
                            <input type="text" name="service_code" value="<?= htmlspecialchars($generated_code) ?>" readonly>
                        </div>
                        <div>
                            <label>IBS Number</label>
                            <input type="text" name="ibs_number" placeholder="IBS-XXXXXX">
                        </div>
                        <div>
                            <label>Service Date <span class="required">*</span></label>
                            <input type="date" name="service_date" value="<?= date('Y-m-d') ?>" required>
                        </div>
                    </div>
                </div>

                <div class="section">
                    <div class="form-grid">
                        <div>
                            <label>Customer Name <span class="required">*</span></label>
                            <input type="text" name="customer_name" required placeholder="Full customer name">
                        </div>
                        <div>
                            <label>Mobile Number <span class="required">*</span></label>
                            <input type="tel" name="mobile_number" required placeholder="+91 9876543210">
                        </div>
                    </div>

                    <div style="margin-top:20px;">
                        <label>Address</label>
                        <textarea name="address" rows="3" placeholder="Full service address"></textarea>
                    </div>
                </div>

                <!-- Dynamic Products -->
                <div class="section">
                    <label>Products / Equipment <span class="required">*</span></label>
                    <div id="productsContainer"></div>
                    <button type="button" class="add-row-btn" onclick="addProductRow()">
                        <i class="fas fa-plus"></i> Add Product Row
                    </button>
                </div>

                <div class="section">
                    <label>Service Description / Problem <span class="required">*</span></label>
                    <textarea name="description" rows="5" required placeholder="Describe the issue or service required..."></textarea>
                </div>

                <div class="form-grid">
                    <div>
                        <label>Status</label>
                        <select name="status">
                            <option value="Pending" selected>Pending</option>
                            <option value="In Progress">In Progress</option>
                            <option value="Completed">Completed</option>
                            <option value="Cancelled">Cancelled</option>
                        </select>
                    </div>
                </div>

                <div class="section">
                    <label>Remarks / Special Instructions</label>
                    <textarea name="remarks" rows="4" placeholder="Any urgency, special requirements..."></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-paper-plane"></i> Create Service Request
                </button>
            </form>
        </div>
    </div>
</div>

<script>

    function searchMaterial(input) {
        const query = input.value.trim();
        const row = input.closest('.item-row');
        let dropdown = row.querySelector('.suggestions') || createDropdown(row, input);

        if (query.length < 2) {
            if (dropdown) dropdown.style.display = 'none';
            return;
        }

        fetch(`search_material.php?name=${encodeURIComponent(query)}`)
            .then(r => r.json())
            .then(data => {
                dropdown.innerHTML = '';
                if (data.length === 0) {
                    dropdown.innerHTML = `<div class="suggestion-item" style="color:#888;">No matching material. Will create new.</div>`;
                } else {
                    data.forEach(item => {
                        const div = document.createElement('div');
                        div.className = 'suggestion-item';
                        div.textContent = item.name + ' (' + (item.sku || 'New') + ')';
                        div.onclick = () => selectTechnician(row, item);
                        dropdown.appendChild(div);
                    });
                }
                dropdown.style.display = 'block';
            });
    }

    function createDropdown(row, input) {
        const div = document.createElement('div');
        div.className = 'suggestions';
        input.parentElement.style.position = 'relative';
        input.parentElement.appendChild(div);
        return div;
    }

    function selectTechnician(row, technician) {
        row.querySelector('[name*="name"]').value = technician.name || '';
        row.querySelector('[name*="technician_code"]').value = technician.technician_code || '';
        

        const dropdown = row.querySelector('.suggestions');
        if (dropdown) dropdown.style.display = 'none';

        calculateRow(row.querySelector('[name*="quantity"]'));
    }
let productCount = 0;
let technicianCount = 0;

function addProductRow() {
    productCount++;
    const html = `
        <div class="product-row" id="prod-${productCount}">
            <button type="button" class="remove-product" onclick="this.parentElement.remove()">×</button>
            <div class="form-grid">
                <div>
                    <label>Model No</label>
                    <input type="text" name="product[${productCount}][model_no]" placeholder="Model number">
                </div>
                <div>
                    <label>Serial No</label>
                    <input type="text" name="product[${productCount}][serial_no]" placeholder="Serial number">
                </div>
                <div class="full-width">
                    <label>Product Name <span class="required">*</span></label>
                    <input type="text" name="product[${productCount}][product_name]" required placeholder="Product / Equipment name">
                </div>
                <div class="full-width">
                    <label>Product Remarks</label>
                    <textarea name="product[${productCount}][remarks]" rows="2" placeholder="Any specific notes about this product"></textarea>
                </div>
            </div>
            <div class="section">
                <label>Technicians</label>
                <div id="techniciansContainer"></div>
                <button type="button" class="add-row-btn" onclick="addTechnicianRow()">
                    <i class="fas fa-plus"></i> Add Technician
                </button>

            </div>
        </div>`;
    
    document.getElementById('productsContainer').insertAdjacentHTML('beforeend', html);
}


function addTechnicianRow() {
    technicianCount++;
    const html = `
        <div class="product-row" id="prod-${technicianCount}">
            <button type="button" class="remove-product" onclick="this.parentElement.remove()">×</button>
            <div class="form-grid">
               <div style="position:relative;">
                        <label> Name</label>
                        <input type="text" name="technician[${technicianCount}][name]" required placeholder="Search or type new material..." onkeyup="searchMaterial(this)">
                </div>
            </div>
        </div>`;
    
    document.getElementById('techniciansContainer').insertAdjacentHTML('beforeend', html);
}
window.onload = () => {
    addProductRow(); // Start with one product row
};
</script>

</body>
</html>

<?php $conn->close(); ?>