<?php
session_start();
require_once "config.php";

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

$agent_id   = (int)($_SESSION['agent_id'] ?? 0);
$agent_name = $_SESSION['agent_name'] ?? 'Support Officer';

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

/*
    IMPORTANT:
    This page is built for the updated flow:
    - user is selected from users table
    - required items are selected with checkboxes
    - request is stored against user_id
    - customer telegram_id is NOT required at request creation time
*/

/* ------------------------------------------------------------------
   OPTIONAL DATABASE UPGRADE NOTE
   ------------------------------------------------------------------
   For best use, add these columns in kyc_verification_requests if missing:

   ALTER TABLE kyc_verification_requests
   ADD COLUMN requested_items TEXT NULL AFTER request_type;

   ALTER TABLE kyc_verification_requests
   MODIFY COLUMN customer_telegram_id BIGINT NULL,
   MODIFY COLUMN request_type VARCHAR(100) NULL,
   MODIFY COLUMN request_title VARCHAR(150) NULL;
------------------------------------------------------------------- */

$requestItemOptions = [
    'selfie_verification' => 'Selfie Verification',
    'video_verification'  => 'Video Verification',
    'passport_image'      => 'Passport Image',
    'id_card_front'       => 'ID Card Front',
    'id_card_back'        => 'ID Card Back',
    'proof_of_address'    => 'Proof of Address',
    'source_of_funds'     => 'Source of Funds Document',
    'custom_document'     => 'Additional Verification Document',
];

function vr_status_class(string $status): string
{
    return match (strtolower($status)) {
        'pending'   => 'badge-pending',
        'submitted' => 'badge-submitted',
        'approved'  => 'badge-approved',
        'rejected'  => 'badge-rejected',
        'expired'   => 'badge-expired',
        default     => 'badge-default',
    };
}

function vr_items_to_labels(?string $json, array $options): string
{
    if (!$json) {
        return '-';
    }

    $decoded = json_decode($json, true);
    if (!is_array($decoded) || empty($decoded)) {
        return '-';
    }

    $labels = [];
    foreach ($decoded as $item) {
        $labels[] = $options[$item] ?? $item;
    }

    return implode(', ', $labels);
}

/* ---------------------------
   USER SEARCH / FETCH
--------------------------- */
$userSearch = trim($_GET['user_search'] ?? '');
$users = [];

try {
    if ($userSearch !== '') {
        $stmtUsers = $pdo->prepare("
            SELECT id, name, email, mobile, account_number, kyc_status, kyc_verified
            FROM users
            WHERE
                name LIKE :search
                OR email LIKE :search
                OR mobile LIKE :search
                OR account_number LIKE :search
            ORDER BY id DESC
            LIMIT 50
        ");
        $stmtUsers->execute([':search' => '%' . $userSearch . '%']);
    } else {
        $stmtUsers = $pdo->query("
            SELECT id, name, email, mobile, account_number, kyc_status, kyc_verified
            FROM users
            ORDER BY id DESC
            LIMIT 30
        ");
    }

    $users = $stmtUsers->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $error = 'Failed to load users: ' . $e->getMessage();
}

/* ---------------------------
   CREATE REQUEST
--------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_request'])) {
    $user_id         = (int)($_POST['user_id'] ?? 0);
    $department      = trim($_POST['department'] ?? '');
    $request_message = trim($_POST['request_message'] ?? '');
    $ticket_id       = trim($_POST['ticket_id'] ?? '');
    $support_chat_id = trim($_POST['support_chat_id'] ?? '');
    $selected_items  = $_POST['requested_items'] ?? [];

    if ($user_id <= 0) {
        $error = 'Please select a valid user.';
    } elseif ($department === '') {
        $error = 'Please enter the requesting department.';
    } elseif (!is_array($selected_items) || empty($selected_items)) {
        $error = 'Please select at least one required verification item.';
    } else {
        $validItems = [];
        foreach ($selected_items as $item) {
            if (isset($requestItemOptions[$item])) {
                $validItems[] = $item;
            }
        }

        if (empty($validItems)) {
            $error = 'Selected verification items are not valid.';
        } else {
            try {
                $stmtUser = $pdo->prepare("
                    SELECT id, name
                    FROM users
                    WHERE id = :id
                    LIMIT 1
                ");
                $stmtUser->execute([':id' => $user_id]);
                $selectedUser = $stmtUser->fetch(PDO::FETCH_ASSOC);

                if (!$selectedUser) {
                    $error = 'The selected user could not be found.';
                } else {
                    $primaryType  = $validItems[0];
                    $requestTitle = 'Verification Required';
                    if (count($validItems) === 1) {
                        $requestTitle = $requestItemOptions[$primaryType] . ' Required';
                    } else {
                        $requestTitle = 'Multiple Verification Items Required';
                    }

                    $requestedItemsJson = json_encode(array_values($validItems), JSON_UNESCAPED_UNICODE);

                    $stmt = $pdo->prepare("
                        INSERT INTO kyc_verification_requests
                        (
                            customer_telegram_id,
                            user_id,
                            customer_name,
                            ticket_id,
                            support_chat_id,
                            department,
                            request_type,
                            request_title,
                            request_message,
                            requested_items,
                            status,
                            created_by_agent_id,
                            created_at,
                            updated_at
                        )
                        VALUES
                        (
                            NULL,
                            :user_id,
                            :customer_name,
                            :ticket_id,
                            :support_chat_id,
                            :department,
                            :request_type,
                            :request_title,
                            :request_message,
                            :requested_items,
                            'pending',
                            :created_by_agent_id,
                            NOW(),
                            NOW()
                        )
                    ");

                    $stmt->execute([
                        ':user_id'             => $selectedUser['id'],
                        ':customer_name'       => $selectedUser['name'],
                        ':ticket_id'           => ($ticket_id !== '' ? $ticket_id : null),
                        ':support_chat_id'     => ($support_chat_id !== '' ? (int)$support_chat_id : null),
                        ':department'          => $department,
                        ':request_type'        => $primaryType,
                        ':request_title'       => $requestTitle,
                        ':request_message'     => ($request_message !== '' ? $request_message : null),
                        ':requested_items'     => $requestedItemsJson,
                        ':created_by_agent_id' => $agent_id,
                    ]);

                    $success = 'Verification request created successfully for the selected user.';
                }
            } catch (Throwable $e) {
                $error = 'Failed to create verification request: ' . $e->getMessage();
            }
        }
    }
}

/* ---------------------------
   LOAD LATEST REQUESTS
--------------------------- */
$latestRequests = [];
try {
    $stmt = $pdo->query("
        SELECT
            id,
            customer_telegram_id,
            user_id,
            customer_name,
            ticket_id,
            support_chat_id,
            department,
            request_type,
            request_title,
            request_message,
            requested_items,
            status,
            created_by_agent_id,
            created_at,
            updated_at
        FROM kyc_verification_requests
        ORDER BY id DESC
        LIMIT 50
    ");
    $latestRequests = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    if ($error === '') {
        $error = 'Failed to load verification requests: ' . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verification Requests - FinoviaPay</title>
    <style>
        *{box-sizing:border-box}
        body{
            margin:0;
            background:#f4f7fb;
            font-family:Arial,Helvetica,sans-serif;
            color:#111827;
        }
        .topbar{
            background:linear-gradient(135deg,#0b4f8a,#0a7b83);
            color:#fff;
            padding:18px 16px;
            box-shadow:0 2px 8px rgba(0,0,0,.10);
        }
        .topbar h1{
            margin:0;
            font-size:22px;
            line-height:1.3;
        }
        .topbar p{
            margin:6px 0 0 0;
            font-size:13px;
            opacity:.94;
        }
        .container{
            max-width:1220px;
            margin:0 auto;
            padding:18px;
        }
        .grid{
            display:grid;
            grid-template-columns:460px 1fr;
            gap:16px;
        }
        .card{
            background:#fff;
            border:1px solid #e5e7eb;
            border-radius:16px;
            box-shadow:0 2px 12px rgba(15,23,42,.06);
            overflow:hidden;
        }
        .card-head{
            padding:16px 18px;
            border-bottom:1px solid #eef2f7;
            background:#fbfcfe;
        }
        .card-head h2{
            margin:0;
            font-size:18px;
            color:#0f172a;
        }
        .card-head p{
            margin:6px 0 0 0;
            font-size:13px;
            color:#6b7280;
        }
        .card-body{
            padding:18px;
        }
        .alert{
            margin-bottom:14px;
            padding:12px 14px;
            border-radius:10px;
            font-size:14px;
        }
        .alert-success{
            background:#eaf7ee;
            color:#166534;
            border:1px solid #bbf7d0;
        }
        .alert-error{
            background:#fef2f2;
            color:#991b1b;
            border:1px solid #fecaca;
        }
        label{
            display:block;
            margin:0 0 7px 0;
            font-size:13px;
            font-weight:700;
            color:#374151;
        }
        .field{
            margin-bottom:14px;
        }
        input, textarea, select{
            width:100%;
            padding:12px;
            border:1px solid #d1d5db;
            border-radius:10px;
            font-size:14px;
            color:#111827;
            background:#fff;
        }
        textarea{
            min-height:110px;
            resize:vertical;
        }
        .row{
            display:grid;
            grid-template-columns:1fr 1fr;
            gap:12px;
        }
        .btn{
            display:inline-block;
            text-decoration:none;
            text-align:center;
            width:100%;
            border:none;
            border-radius:10px;
            background:#0b4f8a;
            color:#fff;
            padding:13px 16px;
            font-size:15px;
            font-weight:700;
            cursor:pointer;
        }
        .btn-light{
            background:#eef4ff;
            color:#0b4f8a;
        }
        .user-search{
            display:grid;
            grid-template-columns:1fr 120px;
            gap:10px;
            margin-bottom:14px;
        }
        .user-list{
            display:grid;
            gap:10px;
            max-height:440px;
            overflow:auto;
            padding-right:2px;
        }
        .user-item{
            border:1px solid #e5e7eb;
            border-radius:12px;
            padding:12px;
            background:#fff;
        }
        .user-item input[type=radio]{
            width:auto;
            margin-right:8px;
            vertical-align:middle;
        }
        .user-line1{
            font-size:14px;
            font-weight:700;
            color:#0b4f8a;
            margin-bottom:4px;
        }
        .user-line2{
            font-size:12px;
            color:#6b7280;
            line-height:1.6;
            word-break:break-word;
        }
        .check-grid{
            display:grid;
            grid-template-columns:1fr 1fr;
            gap:10px;
        }
        .check-item{
            border:1px solid #e5e7eb;
            background:#f9fafb;
            border-radius:12px;
            padding:10px 12px;
            font-size:13px;
            color:#111827;
        }
        .check-item input{
            width:auto;
            margin-right:8px;
            vertical-align:middle;
        }
        .request-list{
            display:grid;
            gap:12px;
        }
        .request-item{
            border:1px solid #e5e7eb;
            border-radius:14px;
            padding:14px;
            background:#fff;
        }
        .request-top{
            display:flex;
            justify-content:space-between;
            align-items:flex-start;
            gap:10px;
            margin-bottom:10px;
        }
        .request-title{
            font-size:16px;
            font-weight:700;
            color:#0b4f8a;
            margin:0;
        }
        .meta{
            display:grid;
            grid-template-columns:repeat(2,1fr);
            gap:10px;
            margin-bottom:10px;
        }
        .meta-box{
            background:#f9fafb;
            border:1px solid #eef2f7;
            border-radius:10px;
            padding:10px;
        }
        .meta-label{
            font-size:11px;
            color:#6b7280;
            margin-bottom:5px;
        }
        .meta-value{
            font-size:13px;
            color:#111827;
            font-weight:600;
            word-break:break-word;
        }
        .desc{
            background:#fbfdff;
            border:1px solid #e8edf3;
            border-radius:10px;
            padding:12px;
            font-size:13px;
            line-height:1.6;
            color:#374151;
            white-space:pre-wrap;
            word-break:break-word;
        }
        .badge{
            display:inline-block;
            padding:6px 10px;
            border-radius:999px;
            font-size:12px;
            font-weight:700;
        }
        .badge-pending{background:#fff7ed;color:#9a3412}
        .badge-submitted{background:#eff6ff;color:#1d4ed8}
        .badge-approved{background:#ecfdf5;color:#047857}
        .badge-rejected{background:#fef2f2;color:#b91c1c}
        .badge-expired{background:#f3f4f6;color:#4b5563}
        .badge-default{background:#f3f4f6;color:#374151}
        .empty{
            text-align:center;
            padding:30px 16px;
            color:#6b7280;
            border:1px dashed #cbd5e1;
            border-radius:14px;
            background:#fff;
        }
        .note{
            margin-top:10px;
            font-size:12px;
            line-height:1.6;
            color:#6b7280;
            background:#f8fafc;
            border:1px solid #e5e7eb;
            border-radius:10px;
            padding:10px 12px;
        }
        @media (max-width: 1024px){
            .grid{grid-template-columns:1fr}
        }
        @media (max-width: 640px){
            .container{padding:12px}
            .row,.meta,.check-grid,.user-search{grid-template-columns:1fr}
            .topbar h1{font-size:19px}
        }
    </style>
</head>
<body>

<div class="topbar">
    <h1>FinoviaPay Verification Requests</h1>
    <p>Officer: <?php echo htmlspecialchars($agent_name); ?> | Create secure KYC / compliance / security verification requirements from the dashboard</p>
</div>

<div class="container">
    <?php if ($success !== ''): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="grid">

        <div class="card">
            <div class="card-head">
                <h2>Create Verification Request</h2>
                <p>Select a user from the banking users table, mark the required items, and create the pending verification request.</p>
            </div>

            <div class="card-body">
                <form method="get" style="margin-bottom:16px;">
                    <div class="user-search">
                        <input type="text" name="user_search" value="<?php echo htmlspecialchars($userSearch); ?>" placeholder="Search user by name, email, mobile, or account number">
                        <button type="submit" class="btn btn-light">Search User</button>
                    </div>
                </form>

                <form method="post">
                    <div class="field">
                        <label>Select User</label>

                        <?php if (!empty($users)): ?>
                            <div class="user-list">
                                <?php foreach ($users as $user): ?>
                                    <label class="user-item">
                                        <input type="radio" name="user_id" value="<?php echo (int)$user['id']; ?>" required>
                                        <span class="user-line1"><?php echo htmlspecialchars($user['name'] ?: 'Unnamed User'); ?></span>
                                        <div class="user-line2">
                                            User ID: <?php echo (int)$user['id']; ?><br>
                                            Mobile: <?php echo htmlspecialchars($user['mobile'] ?? '-'); ?><br>
                                            Email: <?php echo htmlspecialchars($user['email'] ?? '-'); ?><br>
                                            Account Number: <?php echo htmlspecialchars($user['account_number'] ?? '-'); ?><br>
                                            KYC Status: <?php echo htmlspecialchars($user['kyc_status'] ?? '-'); ?> |
                                            Verified: <?php echo !empty($user['kyc_verified']) ? 'Yes' : 'No'; ?>
                                        </div>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="empty">No users were found for the current search.</div>
                        <?php endif; ?>
                    </div>

                    <div class="field">
                        <label>Requesting Department</label>
                        <input type="text" name="department" placeholder="Example: Security Department" required>
                    </div>

                    <div class="field">
                        <label>Required Verification Items</label>
                        <div class="check-grid">
                            <?php foreach ($requestItemOptions as $value => $label): ?>
                                <label class="check-item">
                                    <input type="checkbox" name="requested_items[]" value="<?php echo htmlspecialchars($value); ?>">
                                    <?php echo htmlspecialchars($label); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="row">
                        <div class="field">
                            <label>Ticket ID</label>
                            <input type="text" name="ticket_id" placeholder="Optional ticket ID">
                        </div>
                        <div class="field">
                            <label>Support Chat ID</label>
                            <input type="text" name="support_chat_id" placeholder="Optional chat ID">
                        </div>
                    </div>

                    <div class="field">
                        <label>Request Message / Instructions</label>
                        <textarea name="request_message" placeholder="Write professional instructions for the customer. Example: Please submit a clear face verification video in a well-lit environment."></textarea>
                    </div>

                    <button type="submit" name="create_request" class="btn">Create Verification Request</button>

                    <div class="note">
                        The verification request will be linked to the selected <strong>user account</strong>.  
                        When the customer later identifies their account through Telegram, the pending verification request will be displayed automatically.
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-head">
                <h2>Latest Verification Requests</h2>
                <p>Recent KYC / security / compliance verification requests created from the dashboard.</p>
            </div>

            <div class="card-body">
                <?php if (!empty($latestRequests)): ?>
                    <div class="request-list">
                        <?php foreach ($latestRequests as $req): ?>
                            <div class="request-item">
                                <div class="request-top">
                                    <div>
                                        <div class="request-title"><?php echo htmlspecialchars($req['request_title'] ?? '-'); ?></div>
                                        <div style="font-size:12px;color:#6b7280;margin-top:4px;">
                                            Primary Type: <?php echo htmlspecialchars($requestItemOptions[$req['request_type']] ?? ($req['request_type'] ?? '-')); ?>
                                        </div>
                                    </div>
                                    <span class="badge <?php echo vr_status_class((string)($req['status'] ?? '')); ?>">
                                        <?php echo htmlspecialchars($req['status'] ?? '-'); ?>
                                    </span>
                                </div>

                                <div class="meta">
                                    <div class="meta-box">
                                        <div class="meta-label">User ID</div>
                                        <div class="meta-value"><?php echo htmlspecialchars($req['user_id'] ?? '-'); ?></div>
                                    </div>
                                    <div class="meta-box">
                                        <div class="meta-label">Customer Name</div>
                                        <div class="meta-value"><?php echo htmlspecialchars($req['customer_name'] ?? '-'); ?></div>
                                    </div>
                                    <div class="meta-box">
                                        <div class="meta-label">Department</div>
                                        <div class="meta-value"><?php echo htmlspecialchars($req['department'] ?? '-'); ?></div>
                                    </div>
                                    <div class="meta-box">
                                        <div class="meta-label">Created At</div>
                                        <div class="meta-value"><?php echo htmlspecialchars($req['created_at'] ?? '-'); ?></div>
                                    </div>
                                    <div class="meta-box">
                                        <div class="meta-label">Ticket ID</div>
                                        <div class="meta-value"><?php echo htmlspecialchars($req['ticket_id'] ?? '-'); ?></div>
                                    </div>
                                    <div class="meta-box">
                                        <div class="meta-label">Support Chat ID</div>
                                        <div class="meta-value"><?php echo htmlspecialchars($req['support_chat_id'] ?? '-'); ?></div>
                                    </div>
                                </div>

                                <div class="meta-box" style="margin-bottom:10px;">
                                    <div class="meta-label">Requested Verification Items</div>
                                    <div class="meta-value"><?php echo htmlspecialchars(vr_items_to_labels($req['requested_items'] ?? null, $requestItemOptions)); ?></div>
                                </div>

                                <div class="desc"><?php echo htmlspecialchars($req['request_message'] ?? 'No additional message was provided.'); ?></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty">No verification requests have been created yet.</div>
                <?php endif; ?>
            </div>
        </div>

    </div>
</div>

</body>
</html>
