<?php
// verify_process.php
require 'config/db.php';
require_once 'addons/security_addon.php'; 


// 1. Session & Identity Check
if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$current_user_id = (int)$_SESSION['user_id']; // Direct numeric ID

// 2. LOGIC TO RESEND THE EMAIL
if (isset($_GET['resend'])) {
    try {
        // Fetch User Email and current verification status
        $stmt = $pdo->prepare("SELECT email, is_verified FROM users WHERE id = ?");
        $stmt->execute([$current_user_id]);
        $user = $stmt->fetch();

        if (!$user) { throw new Exception("Account not found."); }
        if ($user['is_verified'] == 1) { header("Location: dashboard.php?info=already_verified"); exit; }

        // Generate a high-entropy 6-digit code
        $new_code = random_int(100000, 999999);
        
        // Update the Vault with the new code
        $update = $pdo->prepare("UPDATE users SET verification_code = ? WHERE id = ?");
        $update->execute([$new_code, $current_user_id]);

        // Send the Mail using your security_addon function
        if (sendVerificationEmail($user['email'], $new_code)) {
            header("Location: dashboard.php?msg=verification_sent");
        } else {
            header("Location: dashboard.php?error=mail_system_offline");
        }
    } catch (Exception $e) {
        error_log("Verification Error: " . $e->getMessage());
        die("System Error: Could not process request.");
    }
}

// 3. LOGIC TO VALIDATE THE CODE (Input from Dashboard)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_now'])) {
    
    // Sanitize input: only keep numbers
    $user_input_code = preg_replace('/[^0-9]/', '', $_POST['code']);

    $stmt = $pdo->prepare("SELECT verification_code FROM users WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $stored_code = $stmt->fetchColumn();

    // Check if code matches and is not empty
    if (!empty($stored_code) && $user_input_code === $stored_code) {
        
        // 4. Verification Success: Update Status and Wipe the Code
        $finalize = $pdo->prepare("UPDATE users SET is_verified = 1, verification_code = NULL WHERE id = ?");
        $finalize->execute([$current_user_id]);
        
        header("Location: dashboard.php?success=account_verified");
        exit;
    } else {
        // Failed attempt
        header("Location: dashboard.php?error=invalid_verification_code");
        exit;
    }
}