<?php
session_start();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'auth/mailer/src/Exception.php';
require 'auth/mailer/src/PHPMailer.php';
require 'auth/mailer/src/SMTP.php';

if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header("Location: admin-login.html");
    exit();
}

require_once('auth/db.php');

$email = $_GET['email'] ?? '';
if (!$email) {
    die("No user specified.");
}

// Check if columns exist first
$columns_result = $conn->query("SHOW COLUMNS FROM users LIKE 'gov_id_path'");
if ($columns_result->num_rows === 0) {
    die("ERROR: KYC columns not found in database. Please run: ALTER TABLE users ADD COLUMN phone VARCHAR(50), ADD COLUMN gov_id_path VARCHAR(500), ADD COLUMN face_photo_path VARCHAR(500);");
}

// Fetch KYC data - only select columns that exist
$stmt = $conn->prepare("SELECT first_name, middle_name, surname, phone, country, gov_id_path, face_photo_path, kyc_status FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($first_name, $middle_name, $surname, $phone, $country, $gov_id_path, $face_photo_path, $kyc_status);

if (!$stmt->fetch()) {
    die("User not found: $email");
}
$stmt->close();

$name = trim($first_name . ' ' . $middle_name . ' ' . $surname);
$govIDPath = $gov_id_path ?? '';
$faceImage = $face_photo_path ?? ''; 
$slogan = "Mine it, Own it, Shape the Future";
$logoUrl = 'https://gobolchain.info/images/gobolcoin-logo.png';

// --- Handle Approve/Reject ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $status = $_POST['decision'] ?? '';
    if (in_array($status, ['Approved', 'Rejected'])) {
        // Update user status
        $update = $conn->prepare("UPDATE users SET kyc_status = ? WHERE email = ?");
        $update->bind_param("ss", $status, $email);
        $update->execute();
        $update->close();

        // Send email notification
        $body = file_get_contents("emails/" . strtolower($status) . "_template.html");
        $body = str_replace(['{{firstName}}', '{{logoUrl}}', '{{slogan}}'], [$first_name, $logoUrl, $slogan], $body);

        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = 'mail.gobolchain.com';  // Fixed: use correct host
            $mail->SMTPAuth = true;
            $mail->Username = 'team@gobolchain.com';  // Fixed: use .com not .info
            $mail->Password = '@Jibala1997';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;

            $mail->setFrom('team@gobolchain.com', 'Gobolchain');
            $mail->addAddress($email, $first_name);
            $mail->isHTML(true);
            $mail->Subject = "KYC Verification $status";
            $mail->Body = $body;
            $mail->send();
        } catch (Exception $e) {
            error_log("Mailer Error: " . $mail->ErrorInfo);
        }

        echo "<script>alert('KYC status updated to $status'); window.location.href='admin-dashboard.php';</script>";
        exit();
    }
}

// Helper to render file previews
function renderFilePreview($filePath) {
    if (!file_exists($filePath)) return "<p>File not found.</p>";
    $mime = mime_content_type($filePath);

    if ($mime === 'application/pdf') {
        return "<iframe src='$filePath' width='100%' height='500px' style='border:1px solid #ccc; border-radius:10px;'></iframe>";
    }

    if (in_array($mime, ['image/jpeg', 'image/jpg', 'image/png'])) {
        return "<img src='$filePath' alt='Uploaded file' class='preview'>";
    }

    return "<p>Unsupported file type.</p>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>KYC Details - Gobolcoin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(to top right, #ffffff 70%, #8B0000 130%);
            padding: 2em;
            color: #333;
        }
        .container {
            max-width: 750px;
            margin: auto;
            background: #fff;
            border-radius: 12px;
            padding: 2em;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        h1 {
            color: #8B0000;
            margin-bottom: 1em;
        }
        .info {
            margin-bottom: 1em;
        }
        .info strong {
            display: inline-block;
            width: 140px;
            color: #600000;
        }
        .preview {
            max-width: 100%;
            height: auto;
            border: 1px solid #ccc;
            margin-top: 0.5em;
            border-radius: 10px;
        }
        iframe {
            width: 100%;
            border: 1px solid #ccc;
            border-radius: 10px;
        }
        .btns {
            margin-top: 2em;
        }
        .btns button {
            padding: 0.8em 1.2em;
            border: none;
            border-radius: 8px;
            margin-right: 1em;
            font-size: 1em;
            cursor: pointer;
            color: #fff;
        }
        .approve { background-color: green; }
        .reject { background-color: red; }
    </style>
</head>
<body>
<div class="container">
    <h1>Review KYC Details</h1>

    <div class="info"><strong>Full Name:</strong> <?= htmlspecialchars($name) ?></div>
    <div class="info"><strong>Email:</strong> <?= htmlspecialchars($email) ?></div>
    <div class="info"><strong>Phone:</strong> <?= htmlspecialchars($phone ?? '') ?></div>
    <div class="info"><strong>Country:</strong> <?= htmlspecialchars($country ?? '') ?></div>

    <div class="info">
        <strong>Government ID:</strong><br>
        <?= $govIDPath ? renderFilePreview($govIDPath) : "<p>No government ID file found.</p>" ?>
    </div>

    <div class="info">
        <strong>Face Photo:</strong><br>
        <?= $faceImage && file_exists($faceImage) ? "<img src='$faceImage' class='preview'>" : "<p>No face image submitted.</p>" ?>
    </div>

    <form method="POST" class="btns">
        <button type="submit" name="decision" value="Approved" class="approve">Approve</button>
        <button type="submit" name="decision" value="Rejected" class="reject">Reject</button>
    </form>
</div>
</body>
</html>