<?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 = 'Complaints';

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

$rows = [];
$tasks = [];
$error = '';
$success = '';

$values = [
    'task_id' => '',
    'complaint_type' => 'service',
    'subject' => '',
    'description' => '',
];

try {
    $pdo = Database::pdo();
    $tasks = $pdo->prepare(
        "SELECT t.task_id, s.service_name, t.scheduled_date, t.status
         FROM tasks t
         JOIN service_requests sr ON t.request_id = sr.request_id
         JOIN services s ON sr.service_id = s.service_id
         WHERE sr.customer_id = :customer_id
         ORDER BY t.scheduled_date DESC, t.task_id DESC"
    );
    $tasks->execute(['customer_id' => $customerId]);
    $tasks = $tasks->fetchAll();

    $stmt = $pdo->prepare(
        "SELECT complaint_id, task_id, complaint_type, subject, description, status, resolution_notes, created_at, resolved_at
         FROM complaints
         WHERE customer_id = :customer_id
         ORDER BY created_at DESC"
    );
    $stmt->execute(['customer_id' => $customerId]);
    $rows = $stmt->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['task_id'] = trim((string)($_POST['task_id'] ?? ''));
    $values['complaint_type'] = trim((string)($_POST['complaint_type'] ?? 'service'));
    $values['subject'] = trim((string)($_POST['subject'] ?? ''));
    $values['description'] = trim((string)($_POST['description'] ?? ''));

    $taskId = (int)$values['task_id'];
    if ($values['subject'] === '' || $values['description'] === '') {
        $error = 'Subject and description are required.';
    } else {
        try {
            $pdo = Database::pdo();

            if ($taskId > 0) {
                $stmtOwn = $pdo->prepare(
                    "SELECT COUNT(*)
                     FROM tasks t
                     JOIN service_requests sr ON t.request_id = sr.request_id
                     WHERE t.task_id = :task_id AND sr.customer_id = :customer_id"
                );
                $stmtOwn->execute(['task_id' => $taskId, 'customer_id' => $customerId]);
                if ((int)$stmtOwn->fetchColumn() <= 0) {
                    throw new RuntimeException('Invalid task selected.');
                }
            } else {
                $taskId = null;
            }

            $stmtIns = $pdo->prepare(
                "INSERT INTO complaints (customer_id, task_id, complaint_type, subject, description, status, created_at)
                 VALUES (:customer_id, :task_id, :complaint_type, :subject, :description, 'pending', CURRENT_TIMESTAMP)"
            );
            $stmtIns->execute([
                'customer_id' => $customerId,
                'task_id' => $taskId,
                'complaint_type' => ($values['complaint_type'] !== '' ? $values['complaint_type'] : 'service'),
                'subject' => $values['subject'],
                'description' => $values['description'],
            ]);

            header('Location: /pest/public/customer/complaints.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' => false],
    ['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' => true],
    ['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; ?>

<?php if ($success !== ''): ?>
    <div class="rounded-xl border border-green-200 bg-green-50 p-4 text-sm text-green-700">
        <?= e($success) ?>
    </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">Complaints</h1>
            <p class="mt-1 text-sm text-slate-600">Submit a complaint and track admin response.</p>
        </div>
    </div>

    <div class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2">
        <div class="rounded-xl border bg-slate-50 p-4">
            <div class="text-sm font-semibold">New Complaint</div>
            <form class="mt-4 space-y-4" method="post" action="">
                <div>
                    <label class="block text-sm font-medium">Related task (optional)</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="task_id">
                        <option value="">No task</option>
                        <?php foreach ($tasks as $t): ?>
                            <option value="<?= e((string)$t['task_id']) ?>" <?= ($values['task_id'] === (string)$t['task_id']) ? 'selected' : '' ?>>
                                #<?= e((string)$t['task_id']) ?> - <?= e((string)$t['service_name']) ?> (<?= e((string)$t['status']) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium">Complaint type</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="complaint_type">
                        <option value="service" <?= ($values['complaint_type'] === 'service') ? 'selected' : '' ?>>service</option>
                        <option value="payment" <?= ($values['complaint_type'] === 'payment') ? 'selected' : '' ?>>payment</option>
                        <option value="staff" <?= ($values['complaint_type'] === 'staff') ? 'selected' : '' ?>>staff</option>
                        <option value="other" <?= ($values['complaint_type'] === 'other') ? 'selected' : '' ?>>other</option>
                    </select>
                </div>

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

                <div>
                    <label class="block text-sm font-medium">Description</label>
                    <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="description" rows="6" required><?= e($values['description']) ?></textarea>
                </div>

                <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 Complaint</button>
            </form>
        </div>

        <div class="rounded-xl border bg-white p-4">
            <div class="text-sm font-semibold">My Complaints</div>
            <div class="mt-3 overflow-x-auto">
                <table class="min-w-full text-sm">
                    <thead class="text-left text-slate-600">
                        <tr class="border-b">
                            <th class="py-2 pr-4">ID</th>
                            <th class="py-2 pr-4">Subject</th>
                            <th class="py-2 pr-4">Task</th>
                            <th class="py-2 pr-4">Status</th>
                            <th class="py-2">Response</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$rows): ?>
                            <tr class="border-b"><td class="py-3 text-slate-500" colspan="5">No complaints yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($rows as $r): ?>
                                <tr class="border-b last:border-0 align-top">
                                    <td class="py-3 pr-4 font-medium">#<?= e((string)$r['complaint_id']) ?></td>
                                    <td class="py-3 pr-4">
                                        <div class="font-medium"><?= e((string)$r['subject']) ?></div>
                                        <div class="text-xs text-slate-500"><?= e((string)$r['created_at']) ?></div>
                                    </td>
                                    <td class="py-3 pr-4"><?= e((string)($r['task_id'] ?? '')) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)$r['status']) ?></td>
                                    <td class="py-3">
                                        <?php if (!empty($r['resolution_notes'])): ?>
                                            <div class="whitespace-pre-wrap text-xs text-slate-700"><?= e((string)$r['resolution_notes']) ?></div>
                                        <?php else: ?>
                                            <span class="text-xs text-slate-500">Waiting for response</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php
$content = ob_get_clean();

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