<?php
require_once __DIR__ . '/config/db.php';
startSession();

// Direct verify without email (for local testing)
if (!empty($_GET['direct']) && !empty($_GET['uid'])) {
    $uid = (int)$_GET['uid'];
    try {
        db()->exec("ALTER TABLE users
            ADD COLUMN IF NOT EXISTS is_email_verified TINYINT(1) NOT NULL DEFAULT 0,
            ADD COLUMN IF NOT EXISTS email_verify_token VARCHAR(100) NULL,
            ADD COLUMN IF NOT EXISTS email_verify_expires DATETIME NULL");
    } catch(PDOException $e){}
    try {
        db()->prepare("UPDATE users SET is_email_verified=1, email_verify_token=NULL, email_verify_expires=NULL WHERE user_id=?")
           ->execute([$uid]);
    } catch(PDOException $e){}
    header('Location: login.php?msg=verified');
    exit;
}

$token = trim($_GET['token'] ?? '');
if (!$token) { header('Location: login.php'); exit; }

$errMsg = '';
try {
    // Auto create columns if missing
    try {
        db()->exec("ALTER TABLE users
            ADD COLUMN IF NOT EXISTS is_email_verified TINYINT(1) NOT NULL DEFAULT 0,
            ADD COLUMN IF NOT EXISTS email_verify_token VARCHAR(100) NULL,
            ADD COLUMN IF NOT EXISTS email_verify_expires DATETIME NULL");
    } catch(PDOException $e){}

    $q = db()->prepare("SELECT user_id, email_verify_expires, is_email_verified FROM users WHERE email_verify_token=? LIMIT 1");
    $q->execute([$token]);
    $user = $q->fetch();

    if (!$user) {
        $errMsg = 'Invalid or already used verification link.';
    } elseif ($user['is_email_verified']) {
        header('Location: login.php?msg=verified'); exit;
    } elseif (strtotime($user['email_verify_expires']) < time()) {
        $errMsg = 'This link has <strong>expired</strong>. <a href="resend_verify.php">Request a new one →</a>';
    } else {
        // db()->prepare("UPDATE users SET is_email_verified=1, email_verify_token=NULL, email_verify_expires=NULL, updated_at=NOW() WHERE user_id=?")
        //   ->execute([$user['user_id']]);
        // Verify user
db()->prepare("UPDATE users 
    SET is_email_verified=1, 
        email_verify_token=NULL, 
        email_verify_expires=NULL, 
        updated_at=NOW() 
    WHERE user_id=?")
   ->execute([$user['user_id']]);
   
   $getUser = db()->prepare("
    SELECT 
        user_id, 
        email,
        CONCAT(
            first_name, 
            ' ', 
            IFNULL(middle_name, ''), 
            ' ', 
            last_name
        ) AS name
    FROM users 
    WHERE user_id=? 
    LIMIT 1
");
$getUser->execute([$user['user_id']]);
$userData = $getUser->fetch();

// Fetch user details
// $getUser = db()->prepare("SELECT user_id, name, email FROM users WHERE user_id=? LIMIT 1");
// $getUser->execute([$user['user_id']]);
// $userData = $getUser->fetch();

if ($userData) {

    // Check if already exists in authors
    $check = db()->prepare("SELECT id FROM authors WHERE user_id=? LIMIT 1");
    $check->execute([$userData['user_id']]);

    if (!$check->fetch()) {

        // Insert into authors
        $insert = db()->prepare("
            INSERT INTO authors (user_id, name, email, created_at, updated_at)
            VALUES (?, ?, ?, NOW(), NOW())
        ");
        $insert->execute([
            $userData['user_id'],
            $userData['name'],
            $userData['email']
        ]);
    }
}
        header('Location: login.php?msg=verified'); exit;
    }
} catch(PDOException $e) {
    $errMsg = 'Server error: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Verification Failed — communeglobal</title>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body{font-family:'Open Sans',sans-serif;background:#F0F4F8;min-height:100vh;display:flex;align-items:center;justify-content:center}
.box{background:#fff;border-radius:12px;padding:40px 36px;text-align:center;max-width:400px;width:90%;box-shadow:0 4px 24px rgba(0,0,0,.1)}
.icon{font-size:52px;margin-bottom:16px}.title{font-size:20px;font-weight:700;color:#222;margin-bottom:10px}
p{font-size:14px;color:#666;line-height:1.7;margin-bottom:20px}
a{color:#1A7F8E;font-weight:600}
.btn{display:inline-block;padding:11px 28px;background:#1A7F8E;color:#fff;border-radius:6px;font-weight:700;font-size:14px;text-decoration:none}
</style>
</head>
<body>
<div class="box">
  <div class="icon">❌</div>
  <div class="title">Verification Failed</div>
  <p><?= $errMsg ?></p>
  <a href="login.php" class="btn">Go to Sign in</a>
</div>
</body>
</html>