<?php

require_once __DIR__ . "/config.inc.php";
require_once __DIR__ . "/../admin/mail_helper.php";

$errors = [];

$full_name = "";
$phone = "";
$email = "";
$address = "";

/*
|--------------------------------------------------------------------------
| ADMIN EMAIL
|--------------------------------------------------------------------------
*/

$adminEmail = 'Luxorrafinance@gmail.com';

/*
|--------------------------------------------------------------------------
| Registration
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /*
    |--------------------------------------------------------------------------
    | CSRF
    |--------------------------------------------------------------------------
    */

    try {

        user_check_csrf();

    } catch (Throwable $e) {

        $errors[] = "Invalid CSRF token. Refresh and try again.";
    }


    /*
    |--------------------------------------------------------------------------
    | Get Form Data
    |--------------------------------------------------------------------------
    */

    $full_name = trim($_POST['full_name'] ?? '');
    $phone     = trim($_POST['phone'] ?? '');
    $email     = trim($_POST['email'] ?? '');
    $address   = trim($_POST['address'] ?? '');

    $password  = $_POST['password'] ?? '';
    $password2 = $_POST['password2'] ?? '';


    /*
    |--------------------------------------------------------------------------
    | Validation
    |--------------------------------------------------------------------------
    */

    if ($full_name === '') {
        $errors[] = "Name is required.";
    }

    if ($phone === '') {
        $errors[] = "Phone is required.";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid email is required.";
    }

    if ($address === '') {
        $errors[] = "Address is required.";
    }

    if (strlen($password) < 6) {
        $errors[] = "Password must be at least 6 characters.";
    }

    if ($password !== $password2) {
        $errors[] = "Passwords do not match.";
    }


    /*
    |--------------------------------------------------------------------------
    | Check Existing Email
    |--------------------------------------------------------------------------
    */

    if (!$errors) {

        $stmt = db()->prepare(
            "SELECT id FROM users WHERE email = ? LIMIT 1"
        );

        $stmt->bind_param(
            "s",
            $email
        );

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {

            $errors[] =
                "Email already registered. Please login.";
        }

        $stmt->close();
    }


    /*
    |--------------------------------------------------------------------------
    | Create User
    |--------------------------------------------------------------------------
    */

    if (!$errors) {

        try {

            /*
            |--------------------------------------------------------------------------
            | Hash Password
            |--------------------------------------------------------------------------
            */

            $hash = password_hash(
                $password,
                PASSWORD_BCRYPT
            );


            /*
            |--------------------------------------------------------------------------
            | New users are PENDING
            |--------------------------------------------------------------------------
            */

            $status = 'pending';


            /*
            |--------------------------------------------------------------------------
            | Insert User
            |--------------------------------------------------------------------------
            */

            $stmt = db()->prepare(
                "INSERT INTO users
                (
                    full_name,
                    phone,
                    email,
                    address,
                    password_hash,
                    status
                )
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?
                )"
            );


            $stmt->bind_param(
                "ssssss",
                $full_name,
                $phone,
                $email,
                $address,
                $hash,
                $status
            );


            $stmt->execute();

            $userId = $stmt->insert_id;

            $stmt->close();


            /*
            |--------------------------------------------------------------------------
            | 1. SEND EMAIL TO ADMIN
            |--------------------------------------------------------------------------
            */

            $adminSubject =
                "New User Registration - besttutor.lk";


            $adminBody = '
            <html>
            <body style="font-family: Arial, sans-serif; line-height: 1.6;">

                <h2>New User Registration</h2>

                <p>
                    A new user has registered on
                    <strong>besttutor.lk</strong>.
                </p>

                <hr>

                <p>
                    <strong>Name:</strong><br>
                    ' . e($full_name) . '
                </p>

                <p>
                    <strong>Phone:</strong><br>
                    ' . e($phone) . '
                </p>

                <p>
                    <strong>Email:</strong><br>
                    ' . e($email) . '
                </p>

                <p>
                    <strong>Address:</strong><br>
                    ' . nl2br(e($address)) . '
                </p>

                <p>
                    <strong>User ID:</strong><br>
                    ' . (int)$userId . '
                </p>

                <hr>

                <p>
                    Account status:
                    <strong style="color: #d97706;">
                        Pending Approval
                    </strong>
                </p>

                <p>
                    Please log in to the admin panel and
                    approve this user.
                </p>

                <p>
                    <strong>besttutor.lk</strong>
                </p>

            </body>
            </html>
            ';


            $adminEmailSent = send_app_email(
                $adminEmail,
                'Administrator',
                $adminSubject,
                $adminBody
            );


            /*
            |--------------------------------------------------------------------------
            | 2. SEND CONFIRMATION EMAIL TO USER
            |--------------------------------------------------------------------------
            */

            $userSubject =
                "Registration Successful - besttutor.lk";


            $userBody = '
            <html>
            <body style="font-family: Arial, sans-serif; line-height: 1.6;">

                <h2 style="color: #198754;">
                    Registration Successful
                </h2>

                <p>
                    Dear <strong>' . e($full_name) . '</strong>,
                </p>

                <p>
                    Thank you for registering with
                    <strong>besttutor.lk</strong>.
                </p>

                <p>
                    Your account has been successfully created.
                </p>

                <table
                    cellpadding="8"
                    cellspacing="0"
                    border="0"
                    style="border-collapse: collapse;"
                >
                    <tr>
                        <td>
                            <strong>Name</strong>
                        </td>
                        <td>
                            ' . e($full_name) . '
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <strong>Email</strong>
                        </td>
                        <td>
                            ' . e($email) . '
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <strong>Phone</strong>
                        </td>
                        <td>
                            ' . e($phone) . '
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <strong>Account Status</strong>
                        </td>
                        <td>
                            <strong style="color: #d97706;">
                                Pending Approval
                            </strong>
                        </td>
                    </tr>
                </table>

                <br>

                <p>
                    Your account is currently waiting for
                    administrator approval.
                </p>

                <p>
                    You will be able to log in once your account
                    has been approved by the administrator.
                </p>

                <p>
                    Please do not share your password with anyone.
                </p>

                <hr>

                <p>
                    Thank you,<br>
                    <strong>besttutor.lk</strong>
                </p>

            </body>
            </html>
            ';


            $userEmailSent = send_app_email(
                $email,
                $full_name,
                $userSubject,
                $userBody
            );


            /*
            |--------------------------------------------------------------------------
            | Log Email Status
            |--------------------------------------------------------------------------
            |
            | Registration should remain successful even if an email fails.
            |
            */

            if (!$adminEmailSent) {
                error_log(
                    "Signup: Admin email failed for User ID " . (int)$userId
                );
            }

            if (!$userEmailSent) {
                error_log(
                    "Signup: User confirmation email failed for User ID " . (int)$userId
                );
            }


            /*
            |--------------------------------------------------------------------------
            | Do NOT log user in
            |--------------------------------------------------------------------------
            */

            redirect(
                'signup_success.php'
            );

        } catch (Throwable $e) {

            /*
            |--------------------------------------------------------------------------
            | Log unexpected registration error
            |--------------------------------------------------------------------------
            */

            error_log(
                'Signup Error: ' . $e->getMessage()
            );

            $errors[] =
                "Could not create your account. Please try again.";
        }
    }
}


require_once __DIR__ . "/partials/header.php";

?>

<div class="row justify-content-center">

    <div class="col-md-7 col-lg-6">

        <div class="card shadow-sm">

            <div class="card-body">

                <h4 class="mb-3">
                    Create Account
                </h4>


                <?php if ($errors): ?>

                    <div class="alert alert-danger">

                        <ul class="mb-0">

                            <?php foreach ($errors as $er): ?>

                                <li>
                                    <?= e($er) ?>
                                </li>

                            <?php endforeach; ?>

                        </ul>

                    </div>

                <?php endif; ?>


                <form
                    method="post"
                    class="row g-3"
                >

                    <input
                        type="hidden"
                        name="csrf_token"
                        value="<?= e(user_csrf()) ?>"
                    >


                    <div class="col-12">

                        <label class="form-label">
                            Full Name
                        </label>

                        <input
                            class="form-control"
                            name="full_name"
                            value="<?= e($full_name) ?>"
                            required
                        >

                    </div>


                    <div class="col-12">

                        <label class="form-label">
                            Phone
                        </label>

                        <input
                            class="form-control"
                            name="phone"
                            value="<?= e($phone) ?>"
                            required
                        >

                    </div>


                    <div class="col-12">

                        <label class="form-label">
                            Email
                        </label>

                        <input
                            class="form-control"
                            type="email"
                            name="email"
                            value="<?= e($email) ?>"
                            required
                        >

                    </div>


                    <div class="col-12">

                        <label class="form-label">
                            Address
                        </label>

                        <textarea
                            class="form-control"
                            name="address"
                            rows="3"
                            required
                        ><?= e($address) ?></textarea>

                    </div>


                    <div class="col-md-6">

                        <label class="form-label">
                            Password
                        </label>

                        <input
                            class="form-control"
                            type="password"
                            name="password"
                            required
                        >

                    </div>


                    <div class="col-md-6">

                        <label class="form-label">
                            Confirm Password
                        </label>

                        <input
                            class="form-control"
                            type="password"
                            name="password2"
                            required
                        >

                    </div>


                    <div class="col-12 d-grid">

                        <button
                            class="btn btn-success"
                            type="submit"
                        >
                            Sign Up
                        </button>

                    </div>


                    <div class="col-12 text-center">

                        Already have an account?

                        <a href="login.php">
                            Login
                        </a>

                    </div>

                </form>

            </div>

        </div>

    </div>

</div>


<?php
require_once __DIR__ . "/partials/footer.php";
?>

