<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';
require_once '../../includes/chat_helper.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureOperationalTables($db);
    ensureAddressAndCallQueueTables($db);
    ensureUnifiedTicketWorkflow($db);
    ensureChatTables($db);

    $csrId = (int)$_SESSION['csr_id'];
    $requestId = (int)($_POST['request_id'] ?? 0);
    $action = strtolower(trim((string)($_POST['action'] ?? '')));
    $rejectReason = trim((string)($_POST['reject_reason'] ?? ''));
    $notes = trim((string)($_POST['notes'] ?? ''));

    if ($requestId <= 0) {
        throw new Exception('Missing request ID.');
    }

    if (!in_array($action, ['approve', 'reject'], true)) {
        throw new Exception('Invalid action.');
    }

    $allowedReasons = [
        'Incomplete details',
        'Invalid contact information',
        'Duplicate request',
        'Outside service area / wrong address',
        'Suspicious or troll request',
        'Customer requested cancellation',
        'Other'
    ];

    if ($action === 'reject' && !in_array($rejectReason, $allowedReasons, true)) {
        throw new Exception('Please select a valid rejection reason.');
    }

    $stmt = $db->prepare("SELECT * FROM service_requests
                          WHERE id = :id
                            AND (source_system = 'php_cx' OR ticket_source IN ('cx_online','customer'))
                          LIMIT 1");
    $stmt->execute([':id' => $requestId]);
    $request = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$request) {
        throw new Exception('Request not found.');
    }

    if (($request['verification_status'] ?? 'approved') !== 'pending') {
        throw new Exception('This request has already been reviewed.');
    }

    $db->beginTransaction();

    if ($action === 'approve') {
        $update = $db->prepare("UPDATE service_requests
                                SET verification_status = 'approved',
                                    verification_reviewed_by = :csr_id,
                                    verification_reviewed_at = NOW(),
                                    verification_reject_reason = NULL,
                                    verification_notes = :notes,
                                    is_fake_ticket = 0,
                                    last_updated_at = NOW()
                                WHERE id = :request_id");
        $update->execute([
            ':csr_id' => $csrId,
            ':notes' => $notes ?: 'Request verified and approved by CSR.',
            ':request_id' => $requestId
        ]);

        try {
            $history = $db->prepare("INSERT INTO request_status_history (request_id, job_status_id, notes, changed_by)
                                     VALUES (:request_id, :job_status_id, :notes, :changed_by)");
            $history->execute([
                ':request_id' => $requestId,
                ':job_status_id' => (int)($request['job_status_id'] ?: 1),
                ':notes' => 'Request verified and approved by CSR.',
                ':changed_by' => 'CSR #' . $csrId
            ]);
        } catch (Throwable $e) {}

        if (!empty($request['customer_id'])) {
            $notif = $db->prepare("INSERT INTO notifications (customer_id, title, message, type, link, created_at)
                                  VALUES (:customer_id, :title, :message, 'success', :link, NOW())");
            $notif->execute([
                ':customer_id' => (int)$request['customer_id'],
                ':title' => 'Service Request Approved',
                ':message' => 'Your service request #' . $request['request_number'] . ' has been verified and accepted by our support team.',
                ':link' => 'my_requests.php?request_id=' . $requestId
            ]);
        }

        $db->commit();

        // Create/activate the customer chat after approval only.
        try {
            $conversation = getOrCreateConversation($db, $requestId, null);
            if ($conversation) {
                addChatMessage(
                    $db,
                    (int)$conversation['id'],
                    $requestId,
                    'system',
                    null,
                    'Your service request #' . $request['request_number'] . ' has been verified and accepted by our support team. You can reply here if you have questions or additional details.',
                    'system',
                    true
                );
            }
        } catch (Throwable $chatError) {}

        echo json_encode(['success' => true, 'message' => 'Request approved and moved to Tickets.']);
        exit;
    }

    // Reject
    $update = $db->prepare("UPDATE service_requests
                            SET verification_status = 'rejected',
                                verification_reviewed_by = :csr_id,
                                verification_reviewed_at = NOW(),
                                verification_reject_reason = :reason,
                                verification_notes = :notes,
                                is_fake_ticket = 1,
                                job_status_id = 5,
                                last_updated_at = NOW()
                            WHERE id = :request_id");
    $update->execute([
        ':csr_id' => $csrId,
        ':reason' => $rejectReason,
        ':notes' => $notes ?: null,
        ':request_id' => $requestId
    ]);

    try {
        $history = $db->prepare("INSERT INTO request_status_history (request_id, job_status_id, notes, changed_by)
                                 VALUES (:request_id, 5, :notes, :changed_by)");
        $history->execute([
            ':request_id' => $requestId,
            ':notes' => 'Request rejected during verification. Reason: ' . $rejectReason . ($notes ? ' Notes: ' . $notes : ''),
            ':changed_by' => 'CSR #' . $csrId
        ]);
    } catch (Throwable $e) {}

    if (!empty($request['customer_id'])) {
        $customerMessage = 'Your service request #' . $request['request_number'] . ' could not be accepted. Reason: ' . $rejectReason . '.';
        if ($notes !== '') {
            $customerMessage .= ' Note: ' . $notes;
        }
        $notif = $db->prepare("INSERT INTO notifications (customer_id, title, message, type, link, created_at)
                              VALUES (:customer_id, :title, :message, 'danger', :link, NOW())");
        $notif->execute([
            ':customer_id' => (int)$request['customer_id'],
            ':title' => 'Service Request Not Accepted',
            ':message' => $customerMessage,
            ':link' => 'my_requests.php?request_id=' . $requestId
        ]);
    }

    $db->commit();

    echo json_encode(['success' => true, 'message' => 'Request rejected and marked as invalid/fake.']);
} catch (Throwable $e) {
    if (isset($db) && $db instanceof PDO && $db->inTransaction()) {
        $db->rollBack();
    }
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
