<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['customer']);

$user = auth_user();
$title = 'Request Service';

$customerId = (int)($user['user_id'] ?? 0);

$services = [];
$error = '';

function table_columns(PDO $pdo, string $table): array
{
    $stmt = $pdo->prepare(
        'SELECT column_name
         FROM information_schema.columns
         WHERE table_schema = DATABASE() AND table_name = :t'
    );
    $stmt->execute(['t' => $table]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN);
}

$values = [
    'service_id' => (string)($_GET['service_id'] ?? ''),
    'preferred_date' => date('Y-m-d'),
    'preferred_time' => '09:00',
    'pest_type' => '',
    'severity_level' => '',
    'property_address' => '',
    'notes' => '',
];

try {
    $pdo = Database::pdo();
    $services = $pdo->query(
        "SELECT service_id, service_name, category, duration_minutes
         FROM services
         WHERE is_active = 1
         ORDER BY service_name ASC"
    )->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($values as $k => $v) {
        $values[$k] = trim((string)($_POST[$k] ?? ''));
    }

    $serviceId = (int)$values['service_id'];

    if ($serviceId <= 0 || $values['preferred_date'] === '' || $values['preferred_time'] === '') {
        $error = 'Please select a service and preferred date/time.';
    } else {
        try {
            $pdo = Database::pdo();
            $cols = table_columns($pdo, 'service_requests');

            $data = [];
            if (in_array('customer_id', $cols, true)) {
                $data['customer_id'] = $customerId;
            }
            if (in_array('service_id', $cols, true)) {
                $data['service_id'] = $serviceId;
            }
            if (in_array('preferred_date', $cols, true)) {
                $data['preferred_date'] = $values['preferred_date'];
            }
            if (in_array('preferred_time', $cols, true)) {
                $data['preferred_time'] = $values['preferred_time'];
            }
            if (in_array('pest_type', $cols, true)) {
                $data['pest_type'] = ($values['pest_type'] !== '' ? $values['pest_type'] : null);
            }
            if (in_array('severity_level', $cols, true)) {
                $data['severity_level'] = ($values['severity_level'] !== '' ? $values['severity_level'] : null);
            }
            if (in_array('property_address', $cols, true)) {
                $data['property_address'] = ($values['property_address'] !== '' ? $values['property_address'] : null);
            } elseif (in_array('address', $cols, true)) {
                $data['address'] = ($values['property_address'] !== '' ? $values['property_address'] : null);
            }
            if (in_array('description', $cols, true)) {
                $data['description'] = ($values['notes'] !== '' ? $values['notes'] : null);
            } elseif (in_array('notes', $cols, true)) {
                $data['notes'] = ($values['notes'] !== '' ? $values['notes'] : null);
            }
            if (in_array('status', $cols, true)) {
                $data['status'] = 'pending';
            }
            if (in_array('created_at', $cols, true)) {
                $data['created_at'] = date('Y-m-d H:i:s');
            }

            if (!$data) {
                throw new RuntimeException('service_requests table columns not compatible.');
            }

            $colNames = array_keys($data);
            $placeholders = [];
            foreach ($colNames as $c) {
                $placeholders[] = ':' . $c;
            }

            $sql = 'INSERT INTO service_requests (' . implode(',', $colNames) . ') VALUES (' . implode(',', $placeholders) . ')';
            $stmt = $pdo->prepare($sql);
            $stmt->execute($data);

            header('Location: /pest/public/customer/index.php');
            exit;
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/customer/overview.php', 'active' => false],
    ['label' => 'My Requests', 'href' => '/pest/public/customer/index.php', 'active' => false],
    ['label' => 'Request Service', 'href' => '/pest/public/customer/request_service.php', 'active' => true],
    ['label' => 'My Services', 'href' => '/pest/public/customer/my_services.php', 'active' => false],
    ['label' => 'Service Reports', 'href' => '/pest/public/customer/reports.php', 'active' => false],
    ['label' => 'IPM Map', 'href' => '/pest/public/customer/ipm_map.php', 'active' => false],
    ['label' => 'Gap Analysis Report', 'href' => '/pest/public/customer/gap_analysis_report.php', 'active' => false],
    ['label' => 'Trend Analysis Report', 'href' => '/pest/public/customer/trend_analysis_report.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/customer/complaints.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/customer/payments.php', 'active' => false],
];

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Request a Service</h1>
            <p class="mt-1 text-sm text-slate-600">Submit a new service request. Admin will assign a staff member.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/customer/index.php">Back</a>
    </div>

    <form class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2" method="post" action="">
        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Service</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="service_id" required>
                <option value="">Select a service</option>
                <?php foreach ($services as $s): ?>
                    <option value="<?= e((string)$s['service_id']) ?>" <?= ($values['service_id'] === (string)$s['service_id']) ? 'selected' : '' ?>>
                        <?= e((string)$s['service_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <label class="block text-sm font-medium">Preferred date</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="date" name="preferred_date" value="<?= e($values['preferred_date']) ?>" required>
        </div>
        <div>
            <label class="block text-sm font-medium">Preferred time</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="time" name="preferred_time" value="<?= e($values['preferred_time']) ?>" required>
        </div>

        <div>
            <label class="block text-sm font-medium">Pest type</label>
            <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="pest_type" value="<?= e($values['pest_type']) ?>" placeholder="e.g. Termites, Cockroaches">
        </div>
        <div>
            <label class="block text-sm font-medium">Severity</label>
            <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="severity_level">
                <option value="" <?= ($values['severity_level'] === '') ? 'selected' : '' ?>>Select</option>
                <option value="low" <?= ($values['severity_level'] === 'low') ? 'selected' : '' ?>>low</option>
                <option value="medium" <?= ($values['severity_level'] === 'medium') ? 'selected' : '' ?>>medium</option>
                <option value="high" <?= ($values['severity_level'] === 'high') ? 'selected' : '' ?>>high</option>
            </select>
        </div>

        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Property / Address</label>
            <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="property_address" rows="3" placeholder="Enter your service address..."><?= e($values['property_address']) ?></textarea>
        </div>

        <div class="md:col-span-2">
            <label class="block text-sm font-medium">Notes</label>
            <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="notes" rows="4" placeholder="Any details for the technician..."><?= e($values['notes']) ?></textarea>
        </div>

        <div class="md:col-span-2">
            <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Submit Request</button>
        </div>
    </form>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
