<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }

    $data = json_decode(file_get_contents("php://input"));

    // Validate required fields
    if (
        empty($data->email) || empty($data->first_name) || empty($data->last_name) ||
        empty($data->phone_number) || empty($data->gender) || empty($data->password)
    ) {
        Helpers::sendResponse(false, 'All fields are required', null, 400);
    }

    // Validate password strength
    if (strlen($data->password) < 6) {
        Helpers::sendResponse(false, 'Password must be at least 6 characters', null, 400);
    }

    $database = new Database();
    $db = $database->getConnection();

    // Check if user exists and is verified
    $query = "SELECT id, is_verified FROM users WHERE email = :email";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $data->email);
    $stmt->execute();

    if ($stmt->rowCount() === 0) {
        Helpers::sendResponse(false, 'User not found', null, 404);
    }

    $user = $stmt->fetch();

    if (!$user['is_verified']) {
        Helpers::sendResponse(false, 'Email not verified', null, 400);
    }

    // Update user details
    $passwordHash = Helpers::hashPassword($data->password);

    $query = "UPDATE users 
          SET `first_name` = :first_name,
              `last_name` = :last_name,
              `phone_number` = :phone_number,
              `gender` = :gender,
              `password` = :password,
              `department_id` = :department,
              `role_id` = :role
          WHERE `id` = :id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':first_name', $data->first_name);
    $stmt->bindParam(':last_name', $data->last_name);
    $stmt->bindParam(':phone_number', $data->phone_number);
    $stmt->bindParam(':gender', $data->gender);
    $stmt->bindParam(':password', $passwordHash);
    $stmt->bindParam(':department', $data->department);
    $stmt->bindParam(':role', $data->role);
    $stmt->bindParam(':id', $user['id']);

    if ($stmt->execute()) {
        // Get updated user data
        $query = "SELECT u.id, u.email, u.first_name, u.last_name, u.phone_number, u.gender, 
                 u.department_id AS department_id, u.role_id, ur.role_name AS role, d.name AS department_name
              FROM users AS u
              JOIN user_roles AS ur ON u.role_id = ur.id
              JOIN departments AS d ON u.department_id = d.id
              WHERE u.id = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $user['id']);
        $stmt->execute();
        $userData = $stmt->fetch();

        // Generate JWT token
        $token = Helpers::createJWT($userData['id'], $userData['email'], $userData['role']);

        Helpers::sendResponse(true, 'Registration completed successfully', [
            'token' => $token,
            'user' => $userData
        ]);
    } else {
        Helpers::sendResponse(false, 'Registration completion failed', null, 500);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $query ?? 'Unknown query', [
        'method' => $method ?? 'Unknown',
        'endpoint' => 'complete-registration'
    ]);
    Helpers::sendResponse(false, 'A database error occurred: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'method' => $method ?? 'Unknown',
        'endpoint' => 'deductions'
    ]);
    Helpers::sendResponse(false, 'An unexpected error occurred: ' . $e->getMessage(), null, 500);
}
