<?php
/**
 * Process Registration OTP Verification & Create Customer Account
 */
require_once 'config.php';
require_once 'auth-helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: register.php');
    exit;
}

$email = trim($_POST['email'] ?? '');
$otp = trim($_POST['otp'] ?? '');
$error = '';

// Validate registration data exists
if (empty($_SESSION['reg_email']) || $_SESSION['reg_email'] !== $email) {
    header('Location: register.php');
    exit;
}

// Validate inputs
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Invalid email address';
} elseif (empty($otp) || strlen($otp) !== 6 || !ctype_digit($otp)) {
    $error = 'Please enter a valid 6-digit OTP';
} else {
    // Verify OTP
    $verifyResult = verifyOTP($conn, $email, $otp);
    
    if ($verifyResult['success']) {
        // Create customer account with registration data from session
        $firstname = $_SESSION['reg_firstname'] ?? '';
        $lastname = $_SESSION['reg_lastname'] ?? '';
        $phone = $_SESSION['reg_phone'] ?? '';
        $hashed_password = $_SESSION['reg_password'] ?? '';

        if (empty($firstname) || empty($lastname) || empty($phone) || empty($hashed_password)) {
            $error = 'Registration data missing. Please try again.';
        } else {
            // Insert new customer
            $insert_query = "INSERT INTO customers (firstname, lastname, email, phone, password, role, created_at, updated_at) 
                            VALUES (?, ?, ?, ?, ?, 'customer', NOW(), NOW())";
            $insert_stmt = $conn->prepare($insert_query);
            
            if ($insert_stmt) {
                $insert_stmt->bind_param("sssss", $firstname, $lastname, $email, $phone, $hashed_password);
                
                if ($insert_stmt->execute()) {
                    // Mark OTP as used
                    markOTPAsUsed($conn, $verifyResult['otp_id']);
                    
                    // Get created user
                    $login_query = "SELECT id, email, firstname, lastname, role FROM customers WHERE email = ? LIMIT 1";
                    $login_stmt = $conn->prepare($login_query);
                    
                    if ($login_stmt) {
                        $login_stmt->bind_param("s", $email);
                        $login_stmt->execute();
                        $login_result = $login_stmt->get_result();
                        
                        if ($login_result->num_rows === 1) {
                            $user = $login_result->fetch_assoc();
                            
                            // Auto-login user
                            $_SESSION['user_id'] = $user['id'];
                            $_SESSION['user_email'] = $user['email'];
                            $_SESSION['user_name'] = $user['firstname'] . ' ' . $user['lastname'];
                            $_SESSION['user_role'] = $user['role'];
                            $_SESSION['login_time'] = time();
                            
                            // Clear registration data from session
                            unset($_SESSION['reg_firstname']);
                            unset($_SESSION['reg_lastname']);
                            unset($_SESSION['reg_email']);
                            unset($_SESSION['reg_phone']);
                            unset($_SESSION['reg_password']);
                            
                            // Redirect to dashboard with success
                            header('Location: dashboards/customer-dashboard.php?success=' . urlencode('Welcome! Your account has been created successfully.'));
                            exit;
                        }
                        $login_stmt->close();
                    }
                } else {
                    $error = 'Failed to create account. Please try again.';
                }
                
                $insert_stmt->close();
            } else {
                $error = 'Database error. Please try again.';
            }
        }
    } else {
        $error = $verifyResult['message'];
    }
}

// Redirect back with error
header('Location: verify-registration-otp.php?email=' . urlencode($email) . '&error=' . urlencode($error));
exit;
?>
