<?php
require_once __DIR__ . '/../../../Models/Customer.php';

class AuthController {
    public function register() {
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['full_name', 'email', 'password']);
        if (!empty($errors)) {
            jsonResponse(false, 'Validation failed', $errors, null, 422);
        }

        $customerModel = new Customer();
        
        if ($customerModel->findByEmail($data['email'])) {
            jsonResponse(false, 'Registration failed', ['email' => 'Email is already registered'], null, 422);
        }

        if (!empty($data['phone']) && $customerModel->findByPhone($data['phone'])) {
            jsonResponse(false, 'Registration failed', ['phone' => 'Phone is already registered'], null, 422);
        }

        $hashedPassword = password_hash($data['password'], PASSWORD_BCRYPT);

        $cityIds = isset($data['city_ids']) && is_array($data['city_ids']) ? $data['city_ids'] : (isset($data['city_id']) ? [$data['city_id']] : []);
        $legacyCityId = !empty($cityIds) ? $cityIds[0] : (isset($data['city_id']) ? $data['city_id'] : null);

        $customerId = $customerModel->insert([
            'full_name' => $data['full_name'],
            'email' => $data['email'],
            'phone_code' => $data['phone_code'] ?? null,
            'phone' => $data['phone'] ?? null,
            'password' => $hashedPassword,
            'preferred_language' => $data['preferred_language'] ?? 'en',
            'city_id' => $legacyCityId,
            'status' => 'active'
        ]);

        $db = Database::getInstance();
        if (!empty($cityIds)) {
            $cityStmt = $db->prepare("INSERT IGNORE INTO customer_cities (customer_id, city_id) VALUES (?, ?)");
            foreach ($cityIds as $cid) {
                $cityStmt->execute([$customerId, $cid]);
            }
        }

        $token = generateJWT(['id' => $customerId, 'type' => 'customer']);

        $customer = $customerModel->find($customerId);
        unset($customer['password']);
        $customer['city_ids'] = $cityIds;

        jsonResponse(true, 'Registration successful', [
            'token' => $token,
            'customer' => $customer
        ]);
    }

    public function login() {
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['email', 'password']);
        if (!empty($errors)) {
            jsonResponse(false, 'Validation failed', $errors, null, 422);
        }

        $customerModel = new Customer();
        $customer = $customerModel->findByEmail($data['email']);

        if (!$customer || !password_verify($data['password'], $customer['password'])) {
            jsonResponse(false, 'Invalid credentials', ['auth' => 'Incorrect email or password'], null, 401);
        }

        if ($customer['status'] !== 'active') {
            jsonResponse(false, 'Account is not active', ['status' => $customer['status']], null, 403);
        }

        $token = generateJWT(['id' => $customer['id'], 'type' => 'customer']);
        unset($customer['password']);

        // Fetch multiple cities
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT city_id FROM customer_cities WHERE customer_id = ?");
        $stmt->execute([$customer['id']]);
        $customer['city_ids'] = $stmt->fetchAll(PDO::FETCH_COLUMN);

        jsonResponse(true, 'Login successful', [
            'token' => $token,
            'customer' => $customer
        ]);
    }

    public function profile() {
        $userId = $GLOBALS['user']['id'];
        $customerModel = new Customer();
        $customer = $customerModel->find($userId);

        if (!$customer) {
            jsonResponse(false, 'Customer not found', [], null, 404);
        }

        unset($customer['password']);

        // Fetch multiple cities
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT city_id FROM customer_cities WHERE customer_id = ?");
        $stmt->execute([$userId]);
        $customer['city_ids'] = $stmt->fetchAll(PDO::FETCH_COLUMN);

        jsonResponse(true, 'Profile loaded', $customer);
    }

    public function forgotPassword() {
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['email']);
        if (!empty($errors)) {
            jsonResponse(false, 'Validation failed', $errors, null, 422);
        }

        $customerModel = new Customer();
        $customer = $customerModel->findByEmail($data['email']);

        if (!$customer) {
            jsonResponse(false, 'Email not found', ['email' => 'No account registered with this email'], null, 404);
        }

        // Mock password reset token
        $resetToken = bin2hex(random_bytes(20));
        
        // Save the reset token in customer's record
        $db = Database::getInstance();
        $stmt = $db->prepare("UPDATE customers SET reset_token = ? WHERE id = ?");
        $stmt->execute([$resetToken, $customer['id']]);

        jsonResponse(true, 'Password reset token generated successfully', [
            'reset_token' => $resetToken
        ]);
    }

    public function resetPassword() {
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['token', 'password']);
        if (!empty($errors)) {
            jsonResponse(false, 'Validation failed', $errors, null, 422);
        }

        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT id FROM customers WHERE reset_token = ? AND status = 'active'");
        $stmt->execute([$data['token']]);
        $customer = $stmt->fetch();

        if (!$customer) {
            jsonResponse(false, 'Invalid or expired token', ['token' => 'Reset token is invalid or expired'], null, 400);
        }

        $hashedPassword = password_hash($data['password'], PASSWORD_BCRYPT);
        $stmt = $db->prepare("UPDATE customers SET password = ?, reset_token = NULL WHERE id = ?");
        $stmt->execute([$hashedPassword, $customer['id']]);

        jsonResponse(true, 'Password reset successfully');
    }

    public function changePassword() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['old_password', 'new_password']);
        if (!empty($errors)) {
            jsonResponse(false, 'Validation failed', $errors, null, 422);
        }

        $customerModel = new Customer();
        $customer = $customerModel->find($customerId);

        if (!$customer || !password_verify($data['old_password'], $customer['password'])) {
            jsonResponse(false, 'Invalid credentials', ['old_password' => 'Incorrect current password'], null, 401);
        }

        $hashedPassword = password_hash($data['new_password'], PASSWORD_BCRYPT);
        $db = Database::getInstance();
        $stmt = $db->prepare("UPDATE customers SET password = ? WHERE id = ?");
        $stmt->execute([$hashedPassword, $customerId]);

        jsonResponse(true, 'Password changed successfully');
    }

    public function updateProfile() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $db = Database::getInstance();

        // Handle multiple locations (cities) if provided
        if (isset($data['city_ids']) && is_array($data['city_ids'])) {
            $cityIds = $data['city_ids'];
            $legacyCityId = !empty($cityIds) ? $cityIds[0] : null;

            // Update legacy city_id on customers table
            $stmt = $db->prepare("UPDATE customers SET city_id = ? WHERE id = ?");
            $stmt->execute([$legacyCityId, $customerId]);

            // Clear old city relations
            $stmt = $db->prepare("DELETE FROM customer_cities WHERE customer_id = ?");
            $stmt->execute([$customerId]);

            // Insert new relations
            if (!empty($cityIds)) {
                $cityStmt = $db->prepare("INSERT IGNORE INTO customer_cities (customer_id, city_id) VALUES (?, ?)");
                foreach ($cityIds as $cid) {
                    $cityStmt->execute([$customerId, $cid]);
                }
            }
        } elseif (isset($data['city_id'])) {
            // Handle legacy single city_id update
            $legacyCityId = $data['city_id'];
            $stmt = $db->prepare("UPDATE customers SET city_id = ? WHERE id = ?");
            $stmt->execute([$legacyCityId, $customerId]);

            $stmt = $db->prepare("DELETE FROM customer_cities WHERE customer_id = ?");
            $stmt->execute([$customerId]);

            if ($legacyCityId) {
                $cityStmt = $db->prepare("INSERT IGNORE INTO customer_cities (customer_id, city_id) VALUES (?, ?)");
                $cityStmt->execute([$customerId, $legacyCityId]);
            }
        }

        $stmt = $db->prepare("
            UPDATE customers 
            SET full_name = ?, 
                phone_code = ?, 
                phone = ?, 
                preferred_language = ?
            WHERE id = ?
        ");

        $stmt->execute([
            $data['full_name'] ?? $payload['full_name'] ?? '',
            $data['phone_code'] ?? null,
            $data['phone'] ?? null,
            $data['preferred_language'] ?? 'en',
            $customerId
        ]);

        $customerModel = new Customer();
        $customer = $customerModel->find($customerId);
        unset($customer['password']);

        // Fetch multiple cities
        $stmt = $db->prepare("SELECT city_id FROM customer_cities WHERE customer_id = ?");
        $stmt->execute([$customerId]);
        $customer['city_ids'] = $stmt->fetchAll(PDO::FETCH_COLUMN);

        jsonResponse(true, 'Profile updated successfully', $customer);
    }
}
