<?php
session_start();
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/vehicle_finance_ai_call_config.php";

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

if (!isset($pdo) || !($pdo instanceof PDO)) {
    die("Database connection not available.");
}

function e($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function vf_ai_log(string $message, array $context = []): void {
    $line = '[' . date('Y-m-d H:i:s') . '] ' . $message;
    if ($context) {
        $line .= ' | ' . json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    @file_put_contents(__DIR__ . '/vehicle_finance_ai_calls.log', $line . PHP_EOL, FILE_APPEND | LOCK_EX);
}

function vf_ai_table(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `telegram_vehicle_finance_ai_calls` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `application_id` INT UNSIGNED NOT NULL,
      `application_reference` VARCHAR(80) DEFAULT NULL,
      `internal_application_id` VARCHAR(80) DEFAULT NULL,
      `target_type` ENUM('applicant','witness_1','witness_2','other') NOT NULL DEFAULT 'applicant',
      `target_name` VARCHAR(255) DEFAULT NULL,
      `phone_number` VARCHAR(50) DEFAULT NULL,
      `call_purpose` VARCHAR(150) DEFAULT 'Vehicle Finance Verification',
      `call_script` LONGTEXT DEFAULT NULL,
      `call_status` ENUM('pending','calling','in_progress','completed','failed','no_answer','dropped','cancelled') NOT NULL DEFAULT 'pending',
      `retell_call_id` VARCHAR(255) DEFAULT NULL,
      `retell_agent_id` VARCHAR(255) DEFAULT NULL,
      `retell_phone_number` VARCHAR(50) DEFAULT NULL,
      `recording_url` TEXT DEFAULT NULL,
      `transcript_text` LONGTEXT DEFAULT NULL,
      `ai_summary` LONGTEXT DEFAULT NULL,
      `ai_extracted_data` LONGTEXT DEFAULT NULL,
      `verification_result` ENUM('pending','verified','incomplete','manual_review','rejected') NOT NULL DEFAULT 'pending',
      `risk_level` ENUM('pending','low','medium','high') NOT NULL DEFAULT 'pending',
      `risk_notes` TEXT DEFAULT NULL,
      `officer_name` VARCHAR(255) DEFAULT NULL,
      `officer_id` VARCHAR(100) DEFAULT NULL,
      `department` VARCHAR(255) DEFAULT 'Vehicle Finance Department',
      `started_at` DATETIME DEFAULT NULL,
      `completed_at` DATETIME DEFAULT NULL,
      `dropped_at` DATETIME DEFAULT NULL,
      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `idx_vf_ai_calls_application_id` (`application_id`),
      KEY `idx_vf_ai_calls_reference` (`application_reference`),
      KEY `idx_vf_ai_calls_status` (`call_status`),
      KEY `idx_vf_ai_calls_retell_call_id` (`retell_call_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}


function vf_ai_questions_table(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `telegram_vehicle_finance_ai_call_questions` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `application_id` INT UNSIGNED NOT NULL,
      `call_id` INT UNSIGNED DEFAULT NULL,
      `target_type` ENUM('applicant','witness_1','witness_2','other') NOT NULL DEFAULT 'witness_1',
      `question_order` INT UNSIGNED NOT NULL DEFAULT 1,
      `question_title` VARCHAR(255) DEFAULT NULL,
      `question_text` TEXT NOT NULL,
      `answer_key` VARCHAR(100) DEFAULT NULL,
      `is_required` TINYINT(1) NOT NULL DEFAULT 1,
      `expected_answer` TEXT DEFAULT NULL,
      `created_by_admin_id` INT DEFAULT NULL,
      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `idx_vf_ai_questions_application` (`application_id`),
      KEY `idx_vf_ai_questions_call` (`call_id`),
      KEY `idx_vf_ai_questions_target` (`target_type`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `telegram_vehicle_finance_ai_call_answers` (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `call_id` INT UNSIGNED NOT NULL,
      `application_id` INT UNSIGNED NOT NULL,
      `question_id` INT UNSIGNED DEFAULT NULL,
      `question_order` INT UNSIGNED DEFAULT NULL,
      `question_text` TEXT DEFAULT NULL,
      `answer_text` LONGTEXT DEFAULT NULL,
      `answer_status` ENUM('answered','not_answered','unclear','refused','matched','mismatch','manual_review') NOT NULL DEFAULT 'answered',
      `confidence_score` DECIMAL(5,2) DEFAULT NULL,
      `extracted_value` TEXT DEFAULT NULL,
      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `idx_vf_ai_answers_call` (`call_id`),
      KEY `idx_vf_ai_answers_application` (`application_id`),
      KEY `idx_vf_ai_answers_question` (`question_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

function vf_ai_get_questions(PDO $pdo, int $applicationId, string $targetType = ''): array {
    vf_ai_questions_table($pdo);
    if ($targetType !== '') {
        $stmt = $pdo->prepare("SELECT * FROM `telegram_vehicle_finance_ai_call_questions` WHERE application_id = :id AND target_type = :target ORDER BY question_order ASC, id ASC");
        $stmt->execute([':id' => $applicationId, ':target' => $targetType]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM `telegram_vehicle_finance_ai_call_questions` WHERE application_id = :id ORDER BY target_type ASC, question_order ASC, id ASC");
        $stmt->execute([':id' => $applicationId]);
    }
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function vf_ai_questions_script(array $questions): string {
    if (!$questions) return '';
    $out = "Advanced verification questions provided by FinoviaPay admin system. Ask these questions one by one and wait for each answer before moving to the next question.\n\n";
    foreach ($questions as $q) {
        $order = (int)($q['question_order'] ?? 1);
        $title = trim((string)($q['question_title'] ?? ''));
        $question = trim((string)($q['question_text'] ?? ''));
        if ($question === '') continue;
        $required = !empty($q['is_required']) ? 'Required' : 'Optional';
        $out .= $order . ". ";
        if ($title !== '') $out .= $title . ": ";
        $out .= $question . " (" . $required . ")\n";
    }
    return $out;
}

function v(array $row, string $key, string $fallback = ''): string {
    $value = $row[$key] ?? $fallback;
    if ($value === null || $value === '') return $fallback;
    return (string)$value;
}

function vf_ai_get_application(PDO $pdo, int $id): array {
    $stmt = $pdo->prepare("SELECT * FROM `telegram_vehicle_finance_applications` WHERE `id` = :id LIMIT 1");
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return is_array($row) ? $row : [];
}

function vf_ai_get_user(PDO $pdo, $userId): array {
    if (!$userId) return [];
    try {
        $stmt = $pdo->prepare("SELECT * FROM `users` WHERE `id` = :id LIMIT 1");
        $stmt->execute([':id' => (int)$userId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return is_array($row) ? $row : [];
    } catch (Throwable $e) {
        return [];
    }
}

function vf_ai_normalize_phone(string $phone): string {
    $phone = trim($phone);
    $phone = str_replace([' ', '-', '(', ')'], '', $phone);
    if ($phone !== '' && $phone[0] !== '+') {
        // Keep original digits but officer should use E.164 format.
        return $phone;
    }
    return $phone;
}

function vf_ai_targets(array $app, array $user): array {
    $applicantPhone = v($app, 'customer_mobile', '');
    if ($applicantPhone === '') $applicantPhone = v($app, 'mobile', '');
    if ($applicantPhone === '') $applicantPhone = v($user, 'mobile', '');

    $w1Name = trim(v($app, 'witness1_first_name') . ' ' . v($app, 'witness1_last_name'));
    $w2Name = trim(v($app, 'witness2_first_name') . ' ' . v($app, 'witness2_last_name'));

    return [
        'applicant' => [
            'label' => 'Applicant',
            'name' => v($app, 'customer_name', v($user, 'name', 'Applicant')),
            'phone' => vf_ai_normalize_phone($applicantPhone),
            'purpose' => 'Applicant Vehicle Finance Verification',
        ],
        'witness_1' => [
            'label' => 'Witness #1',
            'name' => $w1Name !== '' ? $w1Name : 'Witness #1',
            'phone' => vf_ai_normalize_phone(v($app, 'witness1_contact_number')),
            'purpose' => 'Witness #1 Verification',
        ],
        'witness_2' => [
            'label' => 'Witness #2',
            'name' => $w2Name !== '' ? $w2Name : 'Witness #2',
            'phone' => vf_ai_normalize_phone(v($app, 'witness2_contact_number')),
            'purpose' => 'Witness #2 Verification',
        ],
    ];
}

function vf_ai_default_script(array $app, array $target, string $targetType): string {
    $applicantName = v($app, 'customer_name', 'the applicant');
    $targetName = $target['name'] ?? 'the customer';
    $vehicle = trim(v($app, 'vehicle_brand') . ' ' . v($app, 'vehicle_model'));
    if ($vehicle === '') $vehicle = 'the selected vehicle';

    if ($targetType === 'applicant') {
        return "You are a professional banking verification officer from FinoviaPay Vehicle Finance Department.

Your task is to call the applicant and complete a formal vehicle finance verification call.

Important Rules:
- Speak naturally like a real human banking officer.
- Never mention AI, automation, bot, or virtual agent.
- Ask only one question at a time.
- Wait for the answer before asking the next question.
- If the answer is unclear, politely ask for clarification.
- Keep a calm, respectful, and professional banking tone.
- Do not rush the conversation.
- Inform the applicant that the call may be recorded for verification, compliance, and quality assurance purposes.

Call Details:
Applicant Name: {$applicantName}
Application Reference: " . v($app, 'application_reference') . "
Internal Application ID: " . v($app, 'internal_application_id') . "
Vehicle: {$vehicle}

Opening Script:
Hello, this is FinoviaPay Vehicle Finance Verification Department. This call is regarding your vehicle finance application.
Am I speaking with {$applicantName}?

After confirmation say:
Thank you. Before we continue, I would like to inform you that this call may be recorded for verification, compliance, and quality assurance purposes.

Verification Questions:
1. Please confirm your full name.
2. Please confirm your date of birth.
3. Please confirm your National ID or CNIC number.
4. Please confirm your current residential address.
5. Did you apply for vehicle finance through FinoviaPay?
6. Can you confirm the vehicle you selected: {$vehicle}?
7. Please confirm your employment or business status.
8. Are you willing to provide further documents if required by our Vehicle Finance Department?

Closing:
Thank you for your time. Your verification has been completed, and our Vehicle Finance Department will continue reviewing your application.";
    }

    return "You are a professional banking verification officer from FinoviaPay Vehicle Finance Department.

Your task is to call the witness and complete a formal witness verification call regarding a vehicle finance application.

Important Rules:
- Speak naturally like a real human banking officer.
- Never mention AI, automation, bot, or virtual agent.
- Ask only one question at a time.
- Wait for the witness answer before asking the next question.
- If the witness gives an unclear answer, politely ask for clarification.
- If the witness hesitates, reassure them that this is part of a standard banking review and compliance procedure.
- Keep a calm, respectful, and professional banking tone.
- Do not rush the conversation.
- Inform the witness that the call may be recorded for verification, compliance, and quality assurance purposes.

Call Details:
Witness Name: {$targetName}
Applicant Name: {$applicantName}
Application Reference: " . v($app, 'application_reference') . "
Internal Application ID: " . v($app, 'internal_application_id') . "
Vehicle: {$vehicle}

Opening Script:
Hello, this is FinoviaPay Vehicle Finance Verification Department. This call is regarding a vehicle finance verification process.
Am I speaking with {$targetName}?

After confirmation say:
Thank you. Before we continue, I would like to inform you that this call may be recorded for verification, compliance, and quality assurance purposes.

Verification Questions:
1. Please confirm your full name.
2. Please confirm your date of birth.
3. Please confirm your National ID or CNIC number.
4. Please confirm the expiry date of your National ID or CNIC.
5. Please confirm your father name.
6. Please confirm your mother name.
7. Please confirm your current residential address.
8. What is your relationship with {$applicantName}?
9. How long have you known {$applicantName}?
10. Are you aware that {$applicantName} has applied for vehicle finance through FinoviaPay?
11. Can you confirm that you personally know the applicant and are available as a witness/reference if required?

Closing:
Thank you for your time and cooperation. Your witness verification has been completed, and our Vehicle Finance Department will continue reviewing the application.";
}

function vf_ai_call_api(string $method, string $endpoint, array $payload = []): array {
    $apiKey = defined('RETELL_API_KEY') ? RETELL_API_KEY : '';
    if ($apiKey === '' || $apiKey === 'PASTE_RETELL_API_KEY_HERE') {
        return ['ok' => false, 'http' => 0, 'body' => null, 'raw' => 'Retell API key missing in vehicle_finance_ai_call_config.php'];
    }

    $endpointClean = ltrim($endpoint, '/');
    if (str_starts_with($endpointClean, 'v3/')) {
        $apiRoot = preg_replace('#/v2$#', '', rtrim(RETELL_API_BASE, '/'));
        $url = $apiRoot . '/' . $endpointClean;
    } else {
        $url = rtrim(RETELL_API_BASE, '/') . '/' . $endpointClean;
    }

    $ch = curl_init($url);
    $headers = [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ];

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_CUSTOMREQUEST => strtoupper($method),
        CURLOPT_HTTPHEADER => $headers,
    ]);

    if (!empty($payload)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    $raw = curl_exec($ch);
    $err = curl_error($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $body = json_decode((string)$raw, true);

    return [
        'ok' => ($http >= 200 && $http < 300),
        'http' => $http,
        'body' => is_array($body) ? $body : null,
        'raw' => $raw ?: $err,
    ];
}

function vf_ai_extract_call_id(array $body): string {
    foreach (['call_id', 'id'] as $k) {
        if (!empty($body[$k])) return (string)$body[$k];
    }
    return '';
}

function vf_ai_retell_status(string $callId): array {
    if ($callId === '') return ['ok'=>false,'status'=>'','body'=>null,'raw'=>'empty_call_id','http'=>0];
    $res = vf_ai_call_api('GET', 'get-call/' . rawurlencode($callId));
    $status = '';
    if ($res['ok'] && is_array($res['body'])) {
        $status = strtolower((string)($res['body']['call_status'] ?? $res['body']['status'] ?? ''));
    }
    return ['ok'=>$res['ok'],'status'=>$status,'body'=>$res['body'],'raw'=>$res['raw'] ?? '','http'=>$res['http'] ?? 0];
}

function vf_ai_is_retell_live_status(string $status): bool {
    $status = strtolower(trim($status));
    return in_array($status, ['registered','ongoing','in_progress','calling','queued'], true);
}

function vf_ai_find_latest_live_call(array $app, array $callRow): string {
    $targetPhone = preg_replace('/\s+/', '', (string)($callRow['phone_number'] ?? ''));
    $applicationId = (string)($app['id'] ?? $callRow['application_id'] ?? '');
    $applicationRef = (string)($app['application_reference'] ?? $callRow['application_reference'] ?? '');

    $res = vf_ai_call_api('POST', 'v3/list-calls', [
        'limit' => 50,
        'sort_order' => 'descending',
    ]);

    if (!$res['ok'] || !is_array($res['body'])) {
        vf_ai_log('List calls failed while resolving active call', ['response'=>$res]);
        return '';
    }

    $items = $res['body']['items'] ?? [];
    if (!is_array($items)) return '';

    foreach ($items as $item) {
        if (!is_array($item)) continue;
        $status = strtolower((string)($item['call_status'] ?? $item['status'] ?? ''));
        if (!vf_ai_is_retell_live_status($status)) continue;

        $agentId = (string)($item['agent_id'] ?? '');
        if ($agentId !== '' && defined('RETELL_AGENT_ID') && $agentId !== RETELL_AGENT_ID) continue;

        $toNumber = preg_replace('/\s+/', '', (string)($item['to_number'] ?? $item['callee_number'] ?? ''));
        $metadata = $item['metadata'] ?? [];

        $metaAppId = is_array($metadata) ? (string)($metadata['application_id'] ?? '') : '';
        $metaAppRef = is_array($metadata) ? (string)($metadata['application_reference'] ?? '') : '';

        $matchByMeta = ($applicationId !== '' && $metaAppId === $applicationId) || ($applicationRef !== '' && $metaAppRef === $applicationRef);
        $matchByPhone = ($targetPhone !== '' && $toNumber !== '' && $targetPhone === $toNumber);

        if ($matchByMeta || $matchByPhone) {
            return (string)($item['call_id'] ?? '');
        }
    }
    return '';
}

function vf_ai_stop_retell_call(string $callId): array {
    if ($callId === '') return ['ok'=>false,'http'=>0,'raw'=>'No active call id found.'];
    $res = vf_ai_call_api('POST', 'stop-call/' . rawurlencode($callId), []);
    if (($res['http'] ?? 0) === 204) {
        $res['ok'] = true;
        $res['raw'] = 'Call stopped successfully.';
    }
    return $res;
}

function vf_ai_sync_call_from_retell(PDO $pdo, array $callRow): array {
    $callId = (string)($callRow['retell_call_id'] ?? '');
    if ($callId === '') return ['ok' => false, 'message' => 'No Retell call id available.'];

    $res = vf_ai_call_api('GET', 'get-call/' . rawurlencode($callId));
    if (!$res['ok'] || !is_array($res['body'])) {
        return ['ok' => false, 'message' => 'Retell status fetch failed: ' . ($res['raw'] ?? '')];
    }

    $body = $res['body'];
    $status = strtolower((string)($body['call_status'] ?? $body['status'] ?? ''));
    $mapped = 'calling';

    if (in_array($status, ['ended', 'completed'], true)) $mapped = 'completed';
    elseif (in_array($status, ['error', 'failed'], true)) $mapped = 'failed';
    elseif (in_array($status, ['not_connected', 'no_answer'], true)) $mapped = 'no_answer';
    elseif (in_array($status, ['ongoing', 'in_progress'], true)) $mapped = 'in_progress';

    $analysis = $body['call_analysis'] ?? [];
    $summary = is_array($analysis) ? ($analysis['call_summary'] ?? '') : '';
    $custom = is_array($analysis) ? ($analysis['custom_analysis_data'] ?? []) : [];
    $sentiment = is_array($analysis) ? ($analysis['user_sentiment'] ?? '') : '';

    $risk = 'pending';
    $riskNotes = '';
    if (is_array($custom)) {
        $jsonCustom = json_encode($custom, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if (stripos($jsonCustom, 'high') !== false || stripos($jsonCustom, 'suspicious') !== false) $risk = 'high';
        elseif (stripos($jsonCustom, 'medium') !== false) $risk = 'medium';
        elseif ($jsonCustom !== '[]') $risk = 'low';
        $riskNotes = $jsonCustom;
    }

    $stmt = $pdo->prepare("UPDATE `telegram_vehicle_finance_ai_calls`
        SET call_status = :status,
            recording_url = COALESCE(:recording_url, recording_url),
            transcript_text = COALESCE(:transcript, transcript_text),
            ai_summary = COALESCE(:summary, ai_summary),
            ai_extracted_data = COALESCE(:extracted, ai_extracted_data),
            risk_level = :risk,
            risk_notes = COALESCE(:risk_notes, risk_notes),
            completed_at = CASE WHEN :completed = 1 THEN COALESCE(completed_at, NOW()) ELSE completed_at END
        WHERE id = :id LIMIT 1");

    $stmt->execute([
        ':status' => $mapped,
        ':recording_url' => $body['recording_url'] ?? null,
        ':transcript' => $body['transcript'] ?? null,
        ':summary' => $summary ?: null,
        ':extracted' => is_array($custom) ? json_encode($custom, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : null,
        ':risk' => $risk,
        ':risk_notes' => $riskNotes ?: ($sentiment ? 'Sentiment: ' . $sentiment : null),
        ':completed' => $mapped === 'completed' ? 1 : 0,
        ':id' => (int)$callRow['id'],
    ]);

    return ['ok' => true, 'message' => 'Status synced from Retell.'];
}

vf_ai_table($pdo);
vf_ai_questions_table($pdo);

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    die("Invalid application id.");
}

$app = vf_ai_get_application($pdo, $id);
if (!$app) {
    die("Vehicle finance application not found.");
}

$user = vf_ai_get_user($pdo, $app['user_id'] ?? 0);
$targets = vf_ai_targets($app, $user);

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'save_question') {
        $targetTypeQ = trim((string)($_POST['question_target_type'] ?? 'witness_1'));
        $questionOrder = (int)($_POST['question_order'] ?? 1);
        $questionTitle = trim((string)($_POST['question_title'] ?? ''));
        $questionText = trim((string)($_POST['question_text'] ?? ''));
        $answerKey = trim((string)($_POST['answer_key'] ?? ''));
        $isRequired = isset($_POST['is_required']) ? 1 : 0;

        if ($questionText === '') {
            $error = 'Question text is required.';
        } else {
            $stmt = $pdo->prepare("INSERT INTO `telegram_vehicle_finance_ai_call_questions`
                (`application_id`,`target_type`,`question_order`,`question_title`,`question_text`,`answer_key`,`is_required`,`created_by_admin_id`)
                VALUES
                (:application_id,:target_type,:question_order,:question_title,:question_text,:answer_key,:is_required,:created_by_admin_id)");
            $stmt->execute([
                ':application_id' => $id,
                ':target_type' => $targetTypeQ,
                ':question_order' => $questionOrder,
                ':question_title' => $questionTitle,
                ':question_text' => $questionText,
                ':answer_key' => $answerKey,
                ':is_required' => $isRequired,
                ':created_by_admin_id' => (int)($_SESSION['agent_id'] ?? 0),
            ]);
            $success = 'Advanced verification question added successfully.';
        }
    }

    if ($action === 'delete_question') {
        $qid = (int)($_POST['question_id'] ?? 0);
        if ($qid > 0) {
            $stmt = $pdo->prepare("DELETE FROM `telegram_vehicle_finance_ai_call_questions` WHERE id = :qid AND application_id = :app LIMIT 1");
            $stmt->execute([':qid' => $qid, ':app' => $id]);
            $success = 'Verification question deleted successfully.';
        }
    }



    if ($action === 'start_call') {
        $targetType = (string)($_POST['target_type'] ?? 'applicant');
        $target = $targets[$targetType] ?? $targets['applicant'];

        $targetName = trim((string)($_POST['target_name'] ?? $target['name']));
        $phone = vf_ai_normalize_phone((string)($_POST['phone_number'] ?? $target['phone']));
        $purpose = trim((string)($_POST['call_purpose'] ?? $target['purpose']));
        $script = trim((string)($_POST['call_script'] ?? ''));

        if ($script === '') {
            $script = vf_ai_default_script($app, ['name'=>$targetName, 'phone'=>$phone], $targetType);
        }

        $adminQuestions = vf_ai_get_questions($pdo, $id, $targetType);
        $adminQuestionsScript = vf_ai_questions_script($adminQuestions);
        if ($adminQuestionsScript !== '') {
            $script .= "\n\n" . $adminQuestionsScript;
        }

        if ($phone === '' || $phone[0] !== '+') {
            $error = 'Phone number must be in international E.164 format, for example +923001234567.';
        } else {
            $payload = [
                'from_number' => RETELL_FROM_NUMBER,
                'to_number' => $phone,
                'override_agent_id' => RETELL_AGENT_ID,
                'metadata' => [
                    'application_id' => (string)$id,
                    'application_reference' => v($app, 'application_reference'),
                    'internal_application_id' => v($app, 'internal_application_id'),
                    'target_type' => $targetType,
                    'target_name' => $targetName,
                    'source' => 'finoviapay_vehicle_finance_admin'
                ],
                'retell_llm_dynamic_variables' => [
                    'applicant_name' => v($app, 'customer_name', 'Applicant'),
                    'target_name' => $targetName,
                    'target_type' => $target['label'] ?? $targetType,
                    'application_reference' => v($app, 'application_reference'),
                    'internal_application_id' => v($app, 'internal_application_id'),
                    'vehicle_brand' => v($app, 'vehicle_brand'),
                    'vehicle_model' => v($app, 'vehicle_model'),
                    'call_purpose' => $purpose,
                    'verification_script' => $script,
                    'admin_questions' => ''
                ],
                'data_storage_setting' => 'everything'
            ];

            $res = vf_ai_call_api('POST', 'create-phone-call', $payload);
            vf_ai_log('Start call API response', ['http'=>$res['http'], 'body'=>$res['body'], 'raw'=>$res['raw']]);

            if ($res['ok'] && is_array($res['body'])) {
                $retellCallId = vf_ai_extract_call_id($res['body']);

                $stmt = $pdo->prepare("INSERT INTO `telegram_vehicle_finance_ai_calls`
                    (`application_id`,`application_reference`,`internal_application_id`,`target_type`,`target_name`,`phone_number`,`call_purpose`,`call_script`,
                     `call_status`,`retell_call_id`,`retell_agent_id`,`retell_phone_number`,`officer_name`,`officer_id`,`department`,`started_at`)
                    VALUES
                    (:application_id,:application_reference,:internal_application_id,:target_type,:target_name,:phone_number,:call_purpose,:call_script,
                     'calling',:retell_call_id,:retell_agent_id,:retell_phone_number,:officer_name,:officer_id,:department,NOW())");

                $stmt->execute([
                    ':application_id' => $id,
                    ':application_reference' => v($app, 'application_reference'),
                    ':internal_application_id' => v($app, 'internal_application_id'),
                    ':target_type' => $targetType,
                    ':target_name' => $targetName,
                    ':phone_number' => $phone,
                    ':call_purpose' => $purpose,
                    ':call_script' => $script,
                    ':retell_call_id' => $retellCallId,
                    ':retell_agent_id' => RETELL_AGENT_ID,
                    ':retell_phone_number' => RETELL_FROM_NUMBER,
                    ':officer_name' => $_SESSION['agent_name'] ?? 'Admin Officer',
                    ':officer_id' => $_SESSION['agent_id'] ?? '',
                    ':department' => 'Vehicle Finance Department',
                ]);

                $success = 'AI verification call started successfully. Retell Call ID: ' . $retellCallId;
            } else {
                $error = 'Retell call start failed. HTTP ' . $res['http'] . ' — ' . e($res['raw']);
            }
        }
    }

    if ($action === 'refresh_call') {
        $callDbId = (int)($_POST['call_db_id'] ?? 0);
        $stmt = $pdo->prepare("SELECT * FROM `telegram_vehicle_finance_ai_calls` WHERE id = :id AND application_id = :app LIMIT 1");
        $stmt->execute([':id'=>$callDbId, ':app'=>$id]);
        $callRow = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($callRow) {
            $res = vf_ai_sync_call_from_retell($pdo, $callRow);
            $success = $res['ok'] ? $res['message'] : '';
            $error = $res['ok'] ? '' : $res['message'];
        }
    }

    if ($action === 'drop_call') {
        $callDbId = (int)($_POST['call_db_id'] ?? 0);
        $stmt = $pdo->prepare("SELECT * FROM `telegram_vehicle_finance_ai_calls` WHERE id = :id AND application_id = :app LIMIT 1");
        $stmt->execute([':id'=>$callDbId, ':app'=>$id]);
        $callRow = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($callRow) {
            $retellCallId = (string)($callRow['retell_call_id'] ?? '');
            $apiMessage = '';

            if ($retellCallId !== '') {
                $statusCheck = vf_ai_retell_status($retellCallId);
                $activeCallId = $retellCallId;

                if (!$statusCheck['ok'] || !vf_ai_is_retell_live_status($statusCheck['status'])) {
                    $latestLive = vf_ai_find_latest_live_call($app, $callRow);
                    if ($latestLive !== '') {
                        $activeCallId = $latestLive;
                        vf_ai_log('Resolved latest live Retell call id for drop', [
                            'stored_call_id' => $retellCallId,
                            'active_call_id' => $activeCallId,
                            'stored_status' => $statusCheck['status'] ?? ''
                        ]);
                    }
                }

                $res = vf_ai_stop_retell_call($activeCallId);

                if (!$res['ok'] && stripos((string)($res['raw'] ?? ''), 'ongoing') !== false) {
                    $latestLive = vf_ai_find_latest_live_call($app, $callRow);
                    if ($latestLive !== '' && $latestLive !== $activeCallId) {
                        $activeCallId = $latestLive;
                        $res = vf_ai_stop_retell_call($activeCallId);
                    }
                }

                if (($res['http'] ?? 0) === 204 || ($res['ok'] ?? false)) {
                    $apiMessage = ' Retell live call stopped successfully.';
                } else {
                    $apiMessage = ' Retell response HTTP ' . ($res['http'] ?? 0) . ': ' . substr((string)($res['raw'] ?? ''), 0, 300);
                }

                vf_ai_log('Drop call response', [
                    'stored_call_id' => $retellCallId,
                    'active_call_id' => $activeCallId,
                    'stored_status' => $statusCheck['status'] ?? '',
                    'response' => $res
                ]);
            }

            $stmt = $pdo->prepare("UPDATE `telegram_vehicle_finance_ai_calls`
                SET call_status = 'dropped', dropped_at = NOW(), risk_notes = CONCAT(COALESCE(risk_notes,''), :note)
                WHERE id = :id LIMIT 1");
            $stmt->execute([
                ':note' => "\nOfficer manually requested call drop." . $apiMessage,
                ':id' => $callDbId
            ]);

            $success = ($res['ok'] ?? false) ? 'Live call dropped successfully.' . $apiMessage : 'Call marked as dropped locally, but no active Retell call could be stopped.' . $apiMessage;
        }
    }
}

$stmt = $pdo->prepare("SELECT * FROM `telegram_vehicle_finance_ai_calls` WHERE application_id = :id ORDER BY id DESC");
$stmt->execute([':id' => $id]);
$calls = $stmt->fetchAll(PDO::FETCH_ASSOC);

$selectedTarget = $_GET['target'] ?? 'witness_1';
$selectedTarget = isset($targets[$selectedTarget]) ? $selectedTarget : 'witness_1';
$currentTarget = $targets[$selectedTarget];
$defaultScript = vf_ai_default_script($app, $currentTarget, $selectedTarget);
$allVerificationQuestions = vf_ai_get_questions($pdo, $id);
$currentTargetQuestions = vf_ai_get_questions($pdo, $id, $selectedTarget);
$currentQuestionsScript = vf_ai_questions_script($currentTargetQuestions);
if ($currentQuestionsScript !== '') {
    $defaultScript .= "\n\n" . $currentQuestionsScript;
}

function status_badge(string $status): string {
    $s = strtolower($status);
    return match($s) {
        'completed' => 'success',
        'failed','no_answer','dropped','cancelled' => 'danger',
        'in_progress','calling' => 'warning',
        default => 'secondary'
    };
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AI Verification Calls - FinoviaPay</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body{background:#f4f7fb;font-family:Inter,Segoe UI,Arial,sans-serif;color:#182230;}
        .page-wrap{max-width:1180px;margin:auto;padding:18px;}
        .hero-card{background:linear-gradient(135deg,#111827,#0f766e);color:#fff;border-radius:28px;box-shadow:0 24px 60px rgba(15,23,42,.18);}
        .panel-card{background:#fff;border-radius:26px;box-shadow:0 18px 45px rgba(15,23,42,.08);}
        .chip{background:rgba(255,255,255,.16);border:1px solid rgba(255,255,255,.22);border-radius:999px;padding:7px 13px;font-size:13px;}
        .section-title{font-size:20px;font-weight:800;margin-bottom:14px;}
        .info-box{background:#f8fafc;border:1px solid #edf2f7;border-radius:18px;padding:14px;}
        .info-label{font-size:12px;text-transform:uppercase;color:#64748b;font-weight:800;letter-spacing:.04em;}
        .info-value{font-size:15px;font-weight:700;margin-top:4px;word-break:break-word;}
        .btn{border-radius:16px;min-height:46px;font-weight:700;}
        .form-control,.form-select{border-radius:16px;min-height:48px;}
        textarea.form-control{min-height:220px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px;}
        .call-card{border:1px solid #edf2f7;border-radius:22px;padding:16px;background:#fff;}
        .transcript{background:#0b1220;color:#dbeafe;border-radius:18px;padding:14px;white-space:pre-wrap;max-height:280px;overflow:auto;font-size:13px;}
        .script-box{white-space:pre-wrap;background:#f8fafc;border-radius:18px;padding:12px;font-size:13px;max-height:220px;overflow:auto;}
        .question-card{border:1px solid #e5e7eb;border-radius:18px;padding:14px;background:#f8fafc}.question-target{font-size:12px;text-transform:uppercase;color:#475569;font-weight:800}
        @media(max-width:768px){.page-wrap{padding:10px}.hero-card,.panel-card{border-radius:22px}}
@keyframes pulse{0%{opacity:1}50%{opacity:.4}100%{opacity:1}}

</style>
</head>
<body>
<div class="page-wrap">

    <div class="hero-card p-3 p-md-4 mb-3">
        <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
            <div>
                <span class="chip">AI Voice Verification</span>
                <h1 class="h3 mt-3 mb-1">Vehicle Finance AI Calls</h1>
                <div>Application: <?= e(v($app,'application_reference')) ?> · Internal ID: <?= e(v($app,'internal_application_id')) ?></div>
                <div>Customer: <?= e(v($app,'customer_name')) ?></div>
            </div>
            <div class="d-flex gap-2 flex-wrap">
                <a class="btn btn-light" href="admin_vehicle_finance_requests.php">Back List</a>
                <a class="btn btn-outline-light" href="admin_vehicle_finance_request_view.php?id=<?= (int)$id ?>">Open Application</a>
            </div>
        </div>
    </div>

    <?php if ($success): ?><div class="alert alert-success rounded-4"><?= e($success) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger rounded-4"><?= $error ?></div><?php endif; ?>

    <?php if (RETELL_API_KEY === 'PASTE_RETELL_API_KEY_HERE'): ?>
        <div class="alert alert-warning rounded-4">
            Retell API key missing. Open <b>vehicle_finance_ai_call_config.php</b> and paste your API key.
        </div>
    <?php endif; ?>

    
    <?php if (!empty($calls) && !empty($calls[0]['retell_call_id'])): ?>
        <div class="mb-3">
            <a
                href="admin_vehicle_finance_ai_live_monitor.php?id=<?= (int)$id ?>&retell_call_id=<?= urlencode((string)$calls[0]['retell_call_id']) ?>"
                target="_blank"
                class="btn btn-dark"
            >
                🟢 Open Latest Live Monitor
            </a>
        </div>
    <?php endif; ?>

<div class="row g-3">
        <div class="col-12 col-lg-5">
            
            <div class="panel-card p-3 p-md-4 mb-3">
                <div class="section-title">Start AI Verification Call</div>
                <div class="alert alert-info rounded-4">Is page par jo full prompt textarea me likha hoga, call ke waqt AI isi prompt ko follow karegi. Separate question fields ki zarurat nahi.</div>

                <form method="get" class="mb-3">
                    <input type="hidden" name="id" value="<?= (int)$id ?>">
                    <label class="form-label fw-bold">Select Call Target</label>
                    <select name="target" class="form-select" onchange="this.form.submit()">
                        <?php foreach ($targets as $key => $t): ?>
                            <option value="<?= e($key) ?>" <?= $selectedTarget===$key?'selected':'' ?>>
                                <?= e($t['label']) ?> — <?= e($t['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </form>

                <form method="post">
                    <input type="hidden" name="action" value="start_call">
                    <input type="hidden" name="target_type" value="<?= e($selectedTarget) ?>">

                    <div class="mb-3">
                        <label class="form-label fw-bold">Target Name</label>
                        <input type="text" name="target_name" class="form-control" value="<?= e($currentTarget['name']) ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Phone Number</label>
                        <input type="text" name="phone_number" class="form-control" value="<?= e($currentTarget['phone']) ?>" placeholder="+923001234567">
                        <div class="form-text">Use international E.164 format with + country code.</div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Call Purpose</label>
                        <input type="text" name="call_purpose" class="form-control" value="<?= e($currentTarget['purpose']) ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">Full AI Verification Prompt / Call Script</label>
                        <div class="form-text mb-2">Yahan poora prompt likhein. Call start hoti hi AI isi prompt ko follow karegi. Aap isme introduction, recording notice, witness name, applicant name, aur saare questions same Retell prompt style me likh sakte hain.</div>
                        <textarea name="call_script" class="form-control" style="min-height:420px"><?= e($defaultScript) ?></textarea>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">📞 Start AI Verification Call</button>
                </form>
            </div>

            <div class="panel-card p-3 p-md-4">
                <div class="section-title">Application Quick Info</div>
                <div class="row g-2">
                    <div class="col-12"><?= '<div class="info-box"><div class="info-label">Applicant</div><div class="info-value">'.e(v($app,'customer_name')).'</div></div>' ?></div>
                    <div class="col-12"><?= '<div class="info-box"><div class="info-label">Vehicle</div><div class="info-value">'.e(trim(v($app,'vehicle_brand').' '.v($app,'vehicle_model'))).'</div></div>' ?></div>
                    <div class="col-12"><?= '<div class="info-box"><div class="info-label">Witness #1</div><div class="info-value">'.e($targets['witness_1']['name'].' · '.$targets['witness_1']['phone']).'</div></div>' ?></div>
                    <div class="col-12"><?= '<div class="info-box"><div class="info-label">Witness #2</div><div class="info-value">'.e($targets['witness_2']['name'].' · '.$targets['witness_2']['phone']).'</div></div>' ?></div>
                </div>
            </div>
        </div>

        <div class="col-12 col-lg-7">
            <div class="panel-card p-3 p-md-4">
                <div class="section-title">


Call History & Live Status</div>

                <?php if (!$calls): ?>
                    <div class="alert alert-light border rounded-4 mb-0">No AI verification calls have been started for this application yet.</div>
                <?php endif; ?>

                <div class="d-flex flex-column gap-3">
                    <?php foreach ($calls as $call): ?>
                        <div class="call-card">
                            <div class="d-flex justify-content-between align-items-start gap-2 flex-wrap">
                                <div>
                                    <h5 class="mb-1"><?= e(ucwords(str_replace('_',' ',v($call,'target_type')))) ?> — <?= e(v($call,'target_name')) ?></h5>
                                    <div class="text-muted"><?= e(v($call,'phone_number')) ?> · <?= e(v($call,'created_at')) ?></div>
                                    <div class="small text-muted">Retell Call ID: <?= e(v($call,'retell_call_id','N/A')) ?></div>
                                </div>
                                <span class="badge text-bg-<?= status_badge(v($call,'call_status')) ?> rounded-pill p-2"><?= e(strtoupper(v($call,'call_status'))) ?></span>
                            </div>

                            <div class="row g-2 mt-3">
                                <div class="col-12 col-md-6">
                                    <form method="post">
                                        <input type="hidden" name="action" value="refresh_call">
                                        <input type="hidden" name="call_db_id" value="<?= (int)$call['id'] ?>">
                                        <button class="btn btn-outline-primary w-100">🔄 Refresh From Retell</button>
                                    </form>
                                </div>
                                <div class="col-12 col-md-6">
                                    <form method="post" onsubmit="return confirm('Drop/mark this call as dropped?');">
                                        <input type="hidden" name="action" value="drop_call">
                                        <input type="hidden" name="call_db_id" value="<?= (int)$call['id'] ?>">
                                        <button class="btn btn-outline-danger w-100">⛔ Drop Call</button>
                                    </form>
    
                                <?php if (!empty($call['retell_call_id'])): ?>
                                    <div class="col-12">
                                        <a
                                            href="admin_vehicle_finance_ai_live_monitor.php?id=<?= (int)$id ?>&retell_call_id=<?= urlencode((string)$call['retell_call_id']) ?>"
                                            target="_blank"
                                            class="btn btn-dark w-100"
                                        >
                                            🟢 Open Live Call Monitor
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>

                                <?php if (!empty($call['retell_call_id'])): ?>
                                    <div class="col-12">
                                        <a
                                            href="admin_vehicle_finance_ai_live_monitor.php?id=<?= (int)$id ?>&retell_call_id=<?= urlencode((string)$call['retell_call_id']) ?>"
                                            target="_blank"
                                            class="btn btn-dark w-100"
                                        >
                                            🟢 Open Live Call Monitor
                                        </a>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($call['recording_url'])): ?>
                                <div class="mt-3">
                                    <label class="fw-bold mb-2">Recording</label>
                                    <audio controls class="w-100" src="<?= e($call['recording_url']) ?>"></audio>
                                    <a href="<?= e($call['recording_url']) ?>" target="_blank" class="btn btn-sm btn-light mt-2">Open Recording</a>
                                </div>
                            <?php endif; ?>

                            <?php if (!empty($call['ai_summary'])): ?>
                                <div class="mt-3">
                                    <label class="fw-bold">AI Summary</label>
                                    <div class="info-box"><?= nl2br(e($call['ai_summary'])) ?></div>
                                </div>
                            <?php endif; ?>

                            <?php if (!empty($call['ai_extracted_data'])): ?>
                                <div class="mt-3">
                                    <label class="fw-bold">Extracted Verification Data</label>
                                    <div class="script-box"><?= e($call['ai_extracted_data']) ?></div>
                                </div>
                            <?php endif; ?>

                            <?php if (!empty($call['transcript_text'])): ?>
                                <div class="mt-3">
                                    <label class="fw-bold">Full Transcript</label>
                                    <div class="transcript"><?= e($call['transcript_text']) ?></div>
                                </div>
                            <?php endif; ?>

                            <div class="mt-3">
                                <details>
                                    <summary class="fw-bold">Call Script Used</summary>
                                    <div class="script-box mt-2"><?= e(v($call,'call_script')) ?></div>
                                </details>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

            </div>
        </div>
    </div>
</div>
</body>
</html>
