<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once "db_connect.php";

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

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

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    exit("No form submitted.");
}

// collect raw input first
$first_name = trim($_POST["first_name"] ?? "");
$last_name = trim($_POST["last_name"] ?? "");
$username = trim($_POST["username"] ?? "");
$birthdate = $_POST["birthdate"] ?? null;
$address = trim($_POST["address"] ?? "");
$mobile_number = trim($_POST["mobile_number"] ?? "");
$email = trim($_POST["email"] ?? "");
$raw_password = $_POST["password"] ?? "";
$role = trim($_POST["role"] ?? "customer");

$shop_name = trim($_POST["shop_name"] ?? "");
$shop_type = trim($_POST["shop_type"] ?? "");
$main_services = trim($_POST["main_services"] ?? "");
$business_permit_number = trim($_POST["business_permit_number"] ?? "");
$shop_image_name = null;
$verification_token = bin2hex(random_bytes(32));
$email_verified = 0;

$errors = [];

// whitelist allowed roles
$allowed_roles = ["customer", "admin"];
if (!in_array($role, $allowed_roles, true)) {
    $errors[] = "Invalid role selected.";
}

// required fields
if ($first_name === "") $errors[] = "First name is required.";
if ($last_name === "") $errors[] = "Last name is required.";
if ($username === "") $errors[] = "Username is required.";
if ($address === "") $errors[] = "Address is required.";
if ($mobile_number === "") $errors[] = "Mobile number is required.";
if ($email === "") $errors[] = "Email is required.";
if ($raw_password === "") $errors[] = "Password is required.";

// field format validation
if (!preg_match('/^[a-zA-Z0-9_]{4,20}$/', $username)) {
    $errors[] = "Invalid username. Use 4-20 characters (letters, numbers, underscore only).";
}

if ($email !== "" && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format.";
}

if ($raw_password !== "" && strlen($raw_password) < 8) {
    $errors[] = "Password must be at least 8 characters long.";
}

if ($mobile_number !== "" && !preg_match('/^[0-9]{10,15}$/', $mobile_number)) {
    $errors[] = "Invalid mobile number format.";
}


 //Format validation

if ($username !== "" && !preg_match('/^[a-zA-Z0-9_]{8,20}$/', $username)) {
    $errors[] = "Username must be 8-20 characters and use only letters, numbers, and underscore.";
}

if ($email !== "" && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format.";
}

if ($raw_password !== "" && !preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/', $raw_password)) {
    $errors[] = "Password must be at least 8 characters and include uppercase, lowercase, and a number.";
}


if ($mobile_number !== "" && !preg_match('/^[0-9]{10,15}$/', $mobile_number)) {
    $errors[] = "Invalid mobile number format.";
}

// role-based validation
if ($role === "customer") {
    $shop_name = null;
    $shop_type = null;
    $main_services = null;
    $business_permit_number = null;
} else {
    if ($shop_name === "") $errors[] = "Shop name is required.";
    if ($shop_type === "") $errors[] = "Shop type is required.";
    if ($main_services === "") $errors[] = "Main services are required.";
    if ($business_permit_number === "") $errors[] = "Business permit number is required.";
}
if ($role === "admin") {
    if (!isset($_FILES["shop_image"]) || $_FILES["shop_image"]["error"] === 4) {
        $errors[] = "Shop image is required.";
    }
}

// stop immediately if there are validation errors
if (!empty($errors)) {
    echo "<script>alert('" . addslashes(implode("\\n", $errors)) . "'); window.history.back();</script>";
    exit();
}

/* ===========================
   👉 INSERT IMAGE UPLOAD HERE
   =========================== */

if ($role === "admin" && isset($_FILES["shop_image"]) && $_FILES["shop_image"]["error"] === 0) {

    $upload_dir = "../html/uploads/";

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $ext = pathinfo($_FILES["shop_image"]["name"], PATHINFO_EXTENSION);
    $shop_image_name = uniqid("shop_", true) . "." . strtolower($ext);

    move_uploaded_file($_FILES["shop_image"]["tmp_name"], $upload_dir . $shop_image_name);
}

// account status
$status = ($role === "admin") ? "pending" : "active";

// check duplicates only if needed
if ($email !== "") {
    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $errors[] = "Email already exists.";
    }
    $stmt->close();
}

if ($username !== "") {
    $stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $errors[] = "Username already exists.";
    }
    $stmt->close();
}

if ($mobile_number !== "") {
    $stmt = $conn->prepare("SELECT id FROM users WHERE mobile_number = ?");
    $stmt->bind_param("s", $mobile_number);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $errors[] = "Mobile number already exists.";
    }
    $stmt->close();
}

if ($role === "admin") {
    $clean_tin = str_replace('-', '', $business_permit_number);

    if (!preg_match('/^\d{9}$|^\d{12}$/', $clean_tin)) {
        $errors[] = "Invalid BIR number.";
    }
}



// stop immediately if there are validation errors
if (!empty($errors)) {
    echo "<script>alert('" . addslashes(implode("\\n", $errors)) . "'); window.history.back();</script>";
    exit();
}

// account status
$status = ($role === "admin") ? "pending" : "active";

// hash password only after validation passed
$password = password_hash($raw_password, PASSWORD_DEFAULT);

// insert user
$stmt = $conn->prepare("INSERT INTO users 
    (first_name, last_name, username, birthdate, address, mobile_number, email, shop_name, shop_type, main_services, business_permit_number,  shop_image, password, role, status, email_verified, verification_token) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

if (!$stmt) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param(
    "sssssssssssssssis",
    $first_name,
    $last_name,
    $username,
    $birthdate,
    $address,
    $mobile_number,
    $email,
    $shop_name,
    $shop_type,
    $main_services,
    $business_permit_number,
    $shop_image_name,
    $password,
    $role,
    $status,
    $email_verified,
    $verification_token
);

if ($stmt->execute()) {
    define('BASE_URL', 'http://localhost:8080/taiprint/php');
$verify_link = BASE_URL . "/verify-email.php?token=" . urlencode($verification_token);

    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'taiprintmailer@gmail.com';
        $mail->Password = 'ysyv twcc voml jfqx';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->setFrom('taiprintmailer@gmail.com', 'Taiprint');
        $mail->addAddress($email, $first_name . ' ' . $last_name);

        $mail->isHTML(true);
        $mail->Subject = 'Verify your email';
        $mail->Body = "
            <h2>Email Verification</h2>
            <p>Hello {$first_name},</p>
            <p>Please verify your email by clicking the link below:</p>
            <p><a href='{$verify_link}'>Verify Email</a></p>
            <p>If you did not register, please ignore this email.</p>
        ";
        $mail->AltBody = "Hello {$first_name},\n\nPlease verify your email by clicking this link:\n{$verify_link}\n\nIf you did not register, please ignore this email.";

        $mail->send();

        if ($role === "admin") {
    echo "<script>
        alert('Registration submitted. Please verify your email first. After verification, your account will wait for super admin approval.');
        window.location.href = '../html/index.php';
    </script>";
} else {
    echo "<script>
        alert('Registration successful. Please verify your email first.');
        window.location.href = '../html/index.php';
    </script>";
}
exit;
    } catch (Exception $e) {
        echo "Registered, but email could not be sent. Mailer Error: " . $mail->ErrorInfo;
    }
} else {
    echo "Execute failed: " . $stmt->error;
}

$stmt->close();
$conn->close();
?>