<?php

require_once __DIR__ . '/BaseModel.php';

class UserModel extends BaseModel
{

    protected $table = 'user';

    /**
     * Find user by phone number
     */
    public function findByPhone($phone)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE telepon = ? LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        return $result->fetch_assoc();
    }

    /**
     * Find user by email
     */
    public function findByEmail($email)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE email = ? LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        return $result->fetch_assoc();
    }

    /**
     * Find user by email or phone
     */
    public function findByEmailOrPhone($emailOrPhone)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE email = ? OR telepon = ? LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("ss", $emailOrPhone, $emailOrPhone);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        return $result->fetch_assoc();
    }

    /**
     * Find user by username
     */
    public function findByUsername($username)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE username = ? LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        return $result->fetch_assoc();
    }

    /**
     * Check if phone exists
     */
    public function phoneExists($phone)
    {
        return $this->findByPhone($phone) !== null;
    }

    /**
     * Check if email exists
     */
    public function emailExists($email)
    {
        return $this->findByEmail($email) !== null;
    }

    /**
     * Create new user
     */
    public function createUser($userData)
    {
        // Hash password if provided
        if (isset($userData['password'])) {
            $userData['password'] = password_hash($userData['password'], PASSWORD_DEFAULT);
        }

        // Set default values
        $userData['created_at'] = date('Y-m-d H:i:s');

        return $this->create($userData);
    }

    /**
     * Update user password
     */
    public function updatePassword($userId, $newPassword)
    {
        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

        $stmt = $this->db->prepare("UPDATE {$this->table} SET password = ? WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("si", $hashedPassword, $userId);
        $result = $stmt->execute();
        $affectedRows = $stmt->affected_rows;
        $stmt->close();

        return $affectedRows > 0;
    }

    /**
     * Update user profile
     */
    public function updateProfile($userId, $profileData)
    {
        // Remove password from profile data if present
        unset($profileData['password']);

        $profileData['updated_at'] = date('Y-m-d H:i:s');

        return $this->update($userId, $profileData);
    }

    /**
     * Update profile photo
     */
    public function updateProfilePhoto($userId, $photoPath)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET foto_profil = ?, updated_at = NOW() WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("si", $photoPath, $userId);
        $result = $stmt->execute();
        $affectedRows = $stmt->affected_rows;
        $stmt->close();

        return $affectedRows > 0;
    }

    /**
     * Update FCM token
     */
    public function updateFcmToken($userId, $fcmToken, $deviceType = 'android')
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET fcm_token = ?, device_type = ?, updated_at = NOW() WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("ssi", $fcmToken, $deviceType, $userId);
        $result = $stmt->execute();
        $affectedRows = $stmt->affected_rows;
        $stmt->close();

        return $affectedRows > 0;
    }

    /**
     * Get user profile (safe - without password)
     */
    public function getUserProfile($userId)
    {
        $stmt = $this->db->prepare("
            SELECT 
                id, nama_lengkap, email, telepon, username, alamat, 
                provinsi, kota, kecamatan, kelurahan, foto_profil, 
                created_at, updated_at
            FROM {$this->table} 
            WHERE id = ? 
            LIMIT 1
        ");

        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();

        return $result->fetch_assoc();
    }

    /**
     * Verify password
     */
    public function verifyPassword($userId, $password)
    {
        $user = $this->find($userId);
        if (!$user) {
            return false;
        }

        return password_verify($password, $user['password']);
    }

    /**
     * Update OTP
     */
    public function updateOtp($phone, $otp)
    {
        $stmt = $this->db->prepare("UPDATE {$this->table} SET otp = ? WHERE telepon = ?");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("ss", $otp, $phone);
        $result = $stmt->execute();
        $stmt->close();

        return $result;
    }

    /**
     * Clear OTP
     */
    public function clearOtp($phone)
    {
        return $this->updateOtp($phone, '');
    }

    /**
     * Verify OTP
     */
    public function verifyOtp($phone, $otp)
    {
        $stmt = $this->db->prepare("SELECT * FROM {$this->table} WHERE telepon = ? AND otp = ? LIMIT 1");
        if (!$stmt) {
            throw new Exception("Database prepare error: " . $this->db->error);
        }

        $stmt->bind_param("ss", $phone, $otp);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result->fetch_assoc();
        $stmt->close();

        return $user;
    }
}
