<?php
require_once '../../config.php'; 

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $phone = $_POST['phone'];
    $password = $_POST['password'];
    $email = isset($_POST['email']) ? $_POST['email'] : null;
    $branch_id = $_POST['branch_id']; 
    $type = 0; 

    $check_phone_sql = "SELECT * FROM users WHERE phone = ?";
    $stmt = $conn->prepare($check_phone_sql);
    $stmt->bind_param('s', $phone);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        echo json_encode(["success" => false, "message" => "Phone number already registered"]);
    } else {
        if ($email) {
            $check_email_sql = "SELECT * FROM users WHERE email = ?";
            $stmt = $conn->prepare($check_email_sql);
            $stmt->bind_param('s', $email);
            $stmt->execute();
            $email_result = $stmt->get_result();

            if ($email_result->num_rows > 0) {
                echo json_encode(["success" => false, "message" => "Email already registered"]);
                exit;
            }
        }

        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        $sql = "INSERT INTO users (firstname, lastname, phone, password, email, branch_id, type, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param(
                'sssssis',
                $first_name,
                $last_name,
                $phone,
                $hashed_password,
                $email,
                $branch_id,
                $type
            );

            if ($stmt->execute()) {
                echo json_encode(["success" => true, "message" => "Registration successful"]);
            } else {
                echo json_encode(["success" => false, "message" => "Registration failed. Please try again."]);
            }
            $stmt->close();
        }
    }
    $conn->close();
} else {
    echo json_encode(["success" => false, "message" => "Invalid request method"]);
}
?>