<?php

require_once __DIR__ . '/BaseController.php';
require_once __DIR__ . '/../models/UserModel.php';

class UserController extends BaseController
{

    private $userModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = new UserModel();
    }

    /**
     * Get user profile
     */
    public function getProfile()
    {
        try {
            $this->allowMethod(['GET', 'POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['user_id']);

            $userId = (int) $data['user_id'];

            if ($userId <= 0) {
                Response::validationError('Invalid user_id');
            }

            $profile = $this->userModel->getUserProfile($userId);

            if (!$profile) {
                Response::notFound('User not found');
            }

            // Format response
            $profileData = [
                'id' => (int) $profile['id'],
                'nama_lengkap' => $profile['nama_lengkap'],
                'email' => $profile['email'],
                'telepon' => $profile['telepon'],
                'username' => $profile['username'],
                'alamat' => $profile['alamat'],
                'provinsi' => $profile['provinsi'],
                'kota' => $profile['kota'],
                'kecamatan' => $profile['kecamatan'],
                'kelurahan' => $profile['kelurahan'],
                'foto_profil' => $profile['foto_profil'],
                'created_at' => $profile['created_at'],
                'updated_at' => $profile['updated_at']
            ];

            Response::success('Profile retrieved successfully', $profileData);
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Update user profile
     */
    public function updateProfile()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['user_id', 'nama_lengkap', 'alamat', 'provinsi', 'kota', 'kecamatan', 'kelurahan']);

            $userId = (int) $data['user_id'];

            // Check if user exists
            if (!$this->userModel->find($userId)) {
                Response::notFound('User not found');
            }

            // Prepare update data
            $updateData = [
                'nama_lengkap' => trim($data['nama_lengkap']),
                'alamat' => trim($data['alamat']),
                'provinsi' => trim($data['provinsi']),
                'kota' => trim($data['kota']),
                'kecamatan' => trim($data['kecamatan']),
                'kelurahan' => trim($data['kelurahan'])
            ];

            // Sanitize data
            $updateData = $this->sanitizeInput($updateData);

            $result = $this->userModel->updateProfile($userId, $updateData);

            if ($result) {
                Response::success('Profile updated successfully');
            } else {
                Response::error('Failed to update profile');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Update password
     */
    public function updatePassword()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['id', 'password', 'phone']);

            $userId = (int) $data['id'];
            $password = $data['password'];
            $phone = $data['phone'];

            // Verify user exists and phone matches
            $user = $this->userModel->find($userId);
            if (!$user || $user['telepon'] !== $phone) {
                Response::notFound('User not found or phone number does not match');
            }

            // Validate password length
            if (strlen($password) < 6) {
                Response::validationError('Password must be at least 6 characters long');
            }

            $result = $this->userModel->updatePassword($userId, $password);

            if ($result) {
                Response::success('Password updated successfully');
            } else {
                Response::error('Failed to update password');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Upload profile photo
     */
    public function uploadProfilePhoto()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getPostData();
            $files = $this->getFiles();

            $this->validateRequired($data, ['id']);

            $userId = (int) $data['id'];
            $file = $files['foto'] ?? null;

            if (!$file) {
                Response::validationError('Photo file is required');
            }

            if (!is_numeric($userId) || $userId <= 0) {
                Response::validationError('Invalid user ID');
            }

            // Check file upload errors
            if ($file['error'] !== UPLOAD_ERR_OK) {
                Response::error('File upload error');
            }

            // Validate file size (500KB max)
            $maxSize = 500 * 1024;
            if ($file['size'] > $maxSize) {
                Response::validationError('File size must be less than 500KB');
            }

            // Validate file extension
            $allowed = ['jpg', 'jpeg', 'png', 'webp'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

            if (!in_array($ext, $allowed)) {
                Response::validationError('Only JPG, JPEG, PNG, and WEBP files are allowed');
            }

            // Check if user exists
            if (!$this->userModel->find($userId)) {
                Response::notFound('User not found');
            }

            // Create upload directory if not exists
            $targetDir = __DIR__ . '/../uploads/foto_profile_customer/';
            if (!file_exists($targetDir)) {
                mkdir($targetDir, 0755, true);
            }

            // Generate unique filename
            $filename = 'user_' . $userId . '_' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
            $targetFile = $targetDir . $filename;

            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $targetFile)) {
                // Update database
                $photoPath = 'uploads/foto_profile_customer/' . $filename;
                $result = $this->userModel->updateProfilePhoto($userId, $photoPath);

                if ($result) {
                    Response::success('Profile photo uploaded successfully', ['photo_path' => $photoPath]);
                } else {
                    // Delete uploaded file if database update failed
                    unlink($targetFile);
                    Response::error('Failed to update profile photo in database');
                }
            } else {
                Response::error('Failed to upload file');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Update FCM token
     */
    public function updateFcmToken()
    {
        try {
            $this->allowMethod(['POST']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['fcm_token']);

            $fcmToken = $data['fcm_token'];
            $userId = $data['user_id'] ?? null;
            $phone = $data['telepon'] ?? $data['phone'] ?? null;
            $deviceType = $data['device_type'] ?? 'android';

            // Must have either user_id or phone
            if (empty($userId) && empty($phone)) {
                Response::validationError('user_id or phone is required');
            }

            $user = null;

            // Find user by user_id first
            if (!empty($userId) && is_numeric($userId)) {
                $user = $this->userModel->find($userId);
            }

            // If not found by user_id, try phone
            if (!$user && !empty($phone)) {
                $user = $this->userModel->findByPhone($phone);
            }

            if (!$user) {
                Response::notFound('User not found');
            }

            $result = $this->userModel->updateFcmToken($user['id'], $fcmToken, $deviceType);

            if ($result) {
                Response::success('FCM token updated successfully', [
                    'user_id' => $user['id'],
                    'phone' => $user['telepon']
                ]);
            } else {
                Response::error('Failed to update FCM token');
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }

    /**
     * Check if phone exists
     */
    public function checkPhone()
    {
        try {
            $this->allowMethod(['POST', 'GET']);

            $data = $this->getInputData();
            $this->validateRequired($data, ['phone']);

            $phone = trim($data['phone']);

            if (!$this->validatePhone($phone)) {
                Response::validationError('Invalid phone number format');
            }

            $user = $this->userModel->findByPhone($phone);

            if ($user) {
                Response::success('Phone number is registered', [
                    'exists' => true,
                    'user_id' => $user['id'],
                    'nama' => $user['nama_lengkap']
                ]);
            } else {
                Response::success('Phone number is not registered', [
                    'exists' => false
                ]);
            }
        } catch (Exception $e) {
            $this->handleException($e);
        }
    }
}
