<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require '../../db.php';
require '../helper_functions/data_request.php';

function isNumberUnique($number, $currentId = null) {

    try {
        $phoneQuery = "
            SELECT COUNT(*) AS count 
            FROM property_users_data 
            WHERE (mobile_number = :number OR home_number = :number) 
            AND NOT (id <=> :currentId)
            AND deleted_at IS NULL
        ";

        $phoneQuery1 = "
            SELECT COUNT(*) AS count 
            FROM multi_prop_users 
            WHERE (mobile_number = :number OR home_number = :number) 
            AND NOT (user_assoc <=> :currentId)
            AND deleted_at IS NULL
        ";
    
        $params = [
            'number' => $number,
            'currentId' => $currentId
        ];
    
        $phoneCount = fetchSingleDataWithJoins($phoneQuery, $params)['count'];
        $phoneCount1 = fetchSingleDataWithJoins($phoneQuery1, $params)['count'];
    
        return ($phoneCount + $phoneCount1) === 0;
    } catch (Exception $e) {
        error_log("Error checking number uniqueness: " . $e->getMessage());
        return false;
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $fname = $_POST['fname'] ?? 'none';
    $lname = $_POST['lname'] ?? 'none';
    $email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) : null;
    $mphone = isset($_POST['mobphone']) ? preg_replace('/\D/', '', $_POST['mobphone']) : null;
    $hphone = isset($_POST['homphone']) ? preg_replace('/\D/', '', $_POST['homphone']) : null;

    $password = $_POST['pwd'];
    $passwordConfirm = $_POST['pwdc'];
    $token = $_POST['token'];

    if (empty($fname) || empty($lname) || empty($email) || empty($password) || empty($passwordConfirm)) {
        header("Location: ../../register.php?token=$token&error=emptyinput");
        exit();
    }

    // if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //     header("Location: ../../register.php?token=$token&error=invalidemail");
    //     exit();
    // }

    if ($password !== $passwordConfirm) {
        header("Location: ../../register.php?token=$token&error=passwordsdonotmatch");
        exit();
    }

    try {
        // Check if the token is valid in the invitations table
        $stmt = $pdo->prepare("SELECT * FROM invitations WHERE token = ? AND email = ?");
        $stmt->execute([$token, $email]);
        $invitation = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invitation) {
            $role = $invitation['role'];
            $slots = $invitation['dealer_slots'];
            $company = $invitation['company_name'];

            // Check if the email is already registered
            $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->rowCount() > 0) {
                header("Location: ../../register.php?token=$token&error=emailalreadyexists");
                exit();
            }

            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("INSERT INTO users (company_name, firstname, lastname, email, password, layer) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$company, $fname, $lname, $email, $hashedPassword, $role]);

            $userId = $pdo->lastInsertId();

            $stmt = $pdo->prepare("INSERT INTO profile_photo (user_id, user_type, property_id, location, creator_type, created_by) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$userId, 'users', 0, 'fas fa-user fa-4x', 'users', 2]);

            $photoLoc = $pdo->lastInsertId();

            $filler = ' ';
            $stmt = $pdo->prepare("INSERT INTO users_data (user_id, full_name, photo_loc, city, postal_code, state, street_address) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$userId, $fname.' '.$lname, $photoLoc, $filler, $filler, $filler, $filler]);

            $stmt = $pdo->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, (SELECT id FROM roles WHERE name = ?))");
            if (!$stmt->execute([$userId, $role])) {
                echo "Failed to assign role: " . htmlspecialchars($stmt->errorInfo()[2]);
                exit();
            }

            if ($role === 'dealer' || $role === 'admin') {
                $slotsDefault = 0;
                $stmt = $pdo->prepare("INSERT INTO dealer_slots (dealer_id, slots_avail, slots_used) VALUES (?, ?, ?)");
                $stmt->execute([$userId, $slots, $slotsDefault]);
            }

            $stmt = $pdo->prepare("DELETE FROM invitations WHERE token = ?");
            $stmt->execute([$token]);

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

        // Check if the token is valid in the property_invitations table
        $propertyInvitation = fetchDataSingle('property_invitations', [
            'token' => $token,
            'email' => $email
        ]);

        if ($propertyInvitation) {

            $invitationUser = fetchDataSingle('property_users', ['email' => $email, 'deleted_at' => NULL]);

            $stmt = $pdo->prepare("SELECT * FROM property_users WHERE email = ? AND deleted_at = NULL AND status = 'registered'");
            $stmt->execute([$email]);
            if ($stmt->rowCount() > 0) {
                header("Location: ../../register.php?token=$token&error=emailalreadyexists");
                exit();
            }

            if(!empty($hphone) && !isNumberUnique($hphone, $invitationUser['id'])) {
                $_SESSION['alert']['message'] = "The Home Number is already in use.";
                $_SESSION['alert']['type'] = "danger";
                header("Location: ../../register.php?token=$token");
                exit();
            }

            $datA = fetchData('property_users', ['email' => $email]);
            
            $stmt1 = $pdo->prepare("UPDATE property_users_data SET home_number = ?  WHERE property_user = ?");
            $stmt1->execute([$hphone, $datA[0]['id']]);


            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("UPDATE property_users SET status = 'registered', password = ? WHERE email = ?");
            
            if ($stmt->execute([$hashedPassword, $email])) {

                $stmt = $pdo->prepare("DELETE FROM property_invitations WHERE token = ?");
                $stmt->execute([$token]);

            }else {
                echo "Something went wrong!";
            }          

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

        //  Check `dealer_invitations` table
        $stmt = $pdo->prepare("SELECT * FROM dealer_invitations WHERE token = ? AND email = ?");
        $stmt->execute([$token, $email]);
        $dealerInvitation = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($dealerInvitation) {

            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            // Update the Dealer Admin
            $updateData = [
                'firstname' => $fname,
                'lastname' => $lname,
                'password' => $hashedPassword,
                'status' => 'registered'
            ];
        
            $whereClause = 'email = :email';
            $whereParams = [
                'email' => $email
            ];
        
            $updateSuccess = updateTable('dealer_admins', $updateData, $whereClause, $whereParams);

            // Remove used invitation
            $stmt = $pdo->prepare("DELETE FROM dealer_invitations WHERE token = ?");
            $stmt->execute([$token]);

            header("Location: ../../login.php");
            exit();
        }
        
        header("Location: ../../register.php?token=$token&error=invitationnotfound");
        exit();

    } catch (PDOException $e) {
        error_log("Registration failed: " . $e->getMessage());
        echo "Failed to register. Please try again later.";
        exit();
    }
} else {
    echo "Invalid request method.";
}


