<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['email'])) {
    header("Location: login.php");
    exit();
}

$email = $_SESSION['email'];

$host = 'localhost';
$dbname = 'gobolcha_gobolchain';
$dbuser = 'gobolcha_gobolchain';
$dbpass = '@Jibala1997';

// Initialize variables outside the try block
$firstName = trim($_POST['firstName'] ?? '');
$middleName = trim($_POST['middleName'] ?? '');
$lastName = trim($_POST['lastName'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$country = trim($_POST['country'] ?? '');
$govID_path = null;
$face_photo_path = null;

// Validate all required fields at the start
if (!$firstName || !$lastName || !$phone || !$country || empty($_FILES['govID']['tmp_name']) || empty($_POST['face_image_data'])) {
    die("Missing required fields or face image data.");
}

try {
    // --- Establish a single PDO connection for the entire script ---
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $dbuser, $dbpass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // --- Check KYC status (to prevent overwrites) ---
    $stmt = $pdo->prepare("SELECT kyc_status FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && isset($user['kyc_status']) && $user['kyc_status'] === 'approved') {
        header("Location: profile.php?message=kyc_already_approved");
        exit();
    }

    // --- Directory Setup ---
    $userUploadDir = "kyc_uploads/" . md5($email);
    if (!is_dir($userUploadDir)) {
        if (!mkdir($userUploadDir, 0777, true)) {
            error_log("Failed to create upload directory for user: " . $email);
            die("Failed to create upload directory. Please contact support.");
        }
    }

    // --- Process Gov ID Upload ---
    $govID_tmp = $_FILES['govID']['tmp_name'];
    $govID_name = basename($_FILES['govID']['name']);
    $govID_size = $_FILES['govID']['size'];
    if ($govID_size > 1.5 * 1024 * 1024) {
        die("Government ID too large. Max 1.5MB.");
    }
    $allowedExts = ['jpg', 'jpeg', 'png', 'pdf'];
    $ext = strtolower(pathinfo($govID_name, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExts)) {
        die("Invalid file type. Only JPG, PNG, or PDF allowed.");
    }
    $govID_path = "$userUploadDir/govID_" . time() . ".$ext";
    if (!move_uploaded_file($govID_tmp, $govID_path)) {
        error_log("Failed to move uploaded govID file for user: " . $email);
        die("Failed to upload government ID file.");
    }

    // --- Process Face Image Upload ---
    $dataUrl = $_POST['face_image_data'];
    $commaPosition = strpos($dataUrl, ',');
    if ($commaPosition !== false) {
        $base64Data = substr($dataUrl, $commaPosition + 1);
        $decodedData = base64_decode($base64Data);

        if ($decodedData) {
            $face_filename = $userUploadDir . '/face_' . time() . '.png';
            if (file_put_contents($face_filename, $decodedData)) {
                // Assign the path to the correct variable
                $face_photo_path = $face_filename;
            } else {
                error_log("Failed to save face image file from base64 data for user: " . $email);
                die("Failed to save face image file. Please check server logs.");
            }
        } else {
            error_log("Base64 decode failed for user: " . $email);
            die("Invalid face image data format.");
        }
    } else {
        error_log("Base64 data URL format invalid for user: " . $email);
        die("Invalid face image data format.");
    }

    // --- Final Database Update ---
    $stmt = $pdo->prepare("UPDATE users 
        SET kyc_status = ?, first_name = ?, middle_name = ?, surname = ?, phone = ?, country = ?, gov_id_path = ?, face_photo_path = ? 
        WHERE email = ?");

    $stmt->execute([
        'pending', 
        $firstName, 
        $middleName, 
        $lastName, 
        $phone, 
        $country, 
        $govID_path, 
        $face_photo_path,
        $email
    ]);

    // Send Admin Email
    $to = "admin@gobolcoin.com";
    $subject = "New KYC Submission from $firstName $lastName";
    $message = "A user has submitted KYC.\n" .
               "Name: $firstName $middleName $lastName\n" .
               "Email: $email\n" .
               "Phone: $phone\n" .
               "Country: $country\n" .
               "Login to the admin panel to review: https://gobolchain.info/admin-dashboard.php";
    $headers = "From: no-reply@gobolchain.info";
    mail($to, $subject, $message, $headers);
    
    // Confirmation Email to User
    // (I've removed the email body from this code block for brevity, it's the same as yours)
    $userSubject = "Your KYC Submission was Received - Gobolchain Network";
    $logoUrl = "https://gobolchain.info/images/gobolcoin-logo.png";
    $slogan = "Mine it, Own it, Shape the Future";
    // ... rest of the user email content ...
    $headersUser = "MIME-Version: 1.0" . "\r\n";
    $headersUser .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headersUser .= "From: Gobolchain Network <no-reply@gobolchain.info>" . "\r\n";

    // You need to create the full HTML message content here
    $userMessage = "...Your full HTML email content...";
    // mail($email, $userSubject, $userMessage, $headersUser);

    header("Location: profile.php?kyc_status=pending");
    exit;

} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    die("An error occurred while submitting your KYC. Please try again or contact support.");
}

?>