<?php

session_start();

include "../config/database.php";

if ($_SERVER["REQUEST_METHOD"] != "POST") {

    header("Location: ../register.php");
    exit();

}

// Receive Form Data

$fullname = trim($_POST['fullname']);
$email = trim($_POST['email']);
$phone = preg_replace('/\D/', '', trim($_POST['phone']));

// Validate Nigerian phone number

if (!preg_match('/^(070|080|081|090|091)[0-9]{8}$/', $phone)) {

    $_SESSION['error'] = "Please enter a valid Nigerian phone number.";

    header("Location: ../register.php");
    exit();

}


$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$receipt = $_FILES['receipt'];


$_SESSION['old'] = [

    'fullname' => $fullname,

    'email' => $email,

    'phone' => $phone

];

// Check Empty Fields

if (
    empty($fullname) ||
    empty($phone) ||
    empty($password) ||
    empty($confirm_password)
) {

    $_SESSION['error'] = "Please fill in all required fields.";

    header("Location: ../register.php");

    exit();

}

// Check Receipt Upload

if ($receipt['error'] != 0) {

    $_SESSION['error'] = "Please upload your payment receipt.";

    header("Location: ../register.php");

    exit();

}

// Continue...

// Check if passwords match

if ($password !== $confirm_password) {

   $_SESSION['error'] = "Passwords do not match.";
header("Location: ../register.php");
exit();

}

//=============================
// Validate Receipt
//=============================

$allowed = ['jpg','jpeg','png','pdf'];

$extension = strtolower(pathinfo($receipt['name'], PATHINFO_EXTENSION));

if(!in_array($extension,$allowed)){

    $_SESSION['error']="Receipt must be JPG, PNG or PDF.";

    header("Location: ../register.php");

    exit();

}

$newReceiptName = uniqid("receipt_").".".$extension;

$uploadPath = "../assets/uploads/receipts/".$newReceiptName;

if(!move_uploaded_file($receipt['tmp_name'],$uploadPath)){

    $_SESSION['error']="Receipt upload failed.";

    header("Location: ../register.php");

    exit();

}

// Continue...

// Check if email already exists

if (!empty($email)) {

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $_SESSION['error'] = "Please enter a valid email address.";

        header("Location: ../register.php");
        exit();

    }

    $sql = "SELECT id FROM users WHERE email = ?";

    $stmt = $pdo->prepare($sql);

    $stmt->execute([$email]);

    if ($stmt->rowCount() > 0) {

        $_SESSION['error'] = "This email is already registered.";

        header("Location: ../register.php");
        exit();

    }

}


// Check if phone number already exists

$sql = "SELECT id FROM users WHERE phone = ?";

$stmt = $pdo->prepare($sql);

$stmt->execute([$phone]);

if ($stmt->rowCount() > 0) {

    $_SESSION['error'] = "This phone number is already registered.";
header("Location: ../register.php");
exit();

}

// Continue...

// Hash Password

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// Save User

$sql = "INSERT INTO users
(
fullname,
email,
phone,
wallet_balance,
virtual_bank,
virtual_account_number,
virtual_account_name,
password,
role,
status
)

VALUES
(
?,?,?,?,?,?,?,?,?,?
)";

$stmt = $pdo->prepare($sql);

try {

    $stmt->execute([

        $fullname,
        $email,
        $phone,
        0,
        NULL,
        NULL,
        NULL,
        $hashedPassword,
        'member',
        'pending'

    ]);

} catch (PDOException $e) {

    die($e->getMessage());

}
$userId = $pdo->lastInsertId();
$setting = $pdo->query("SELECT registration_fee FROM settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);

$sql = "INSERT INTO registration_payments
(
user_id,
amount,
receipt,
status
)

VALUES
(
?,?,?,?
)";

$stmt = $pdo->prepare($sql);

try {

    $stmt->execute([

        $userId,

        $setting['registration_fee'],

        $newReceiptName,

        'pending'

    ]);

} catch(PDOException $e){

    die($e->getMessage());

}

unset($_SESSION['old']);

$_SESSION['success']="Registration submitted successfully. Your account is awaiting payment verification.";

header("Location: ../login.php");
exit();

?>