<?php

namespace App\Controllers;

use App\Models\User;
use App\Models\UserComunity;
use App\Models\UserUgel;
use App\Services\UserService;
use Exception;

class ProfileController extends BaseController
{
    protected UserService $userService;

    public function __construct() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $this->userService = new UserService();
    }

    public function index() {
        $user_id = $_SESSION['user_id'];
        $userDetails = null;

        $user = User::find($user_id);

        if($_SESSION['role'] !== 'COMUNITY') {
            $userDetails = UserUgel::findBy('user_id', $user->id);
        } 
        else {
            $userDetails = UserComunity::findBy('user_id', $user->id);
        }

        $this->render('profile/profile-show', ['userDetails' => $userDetails, 'user' => $user]);
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            try {
                $user = UserService::getUser();
    
                $phone = isset($_POST['phone']) && $_POST['phone'] !== '' ? trim($_POST['phone']) : null;
                $address = isset($_POST['address']) && $_POST['address'] !== '' ? trim($_POST['address']) : null;
    
                $user->phone = $phone;
                $user->address = $address;
    
                if ($_SESSION['role'] === 'COMUNITY') {
                    $user->company_name = isset($_POST['company_name']) && $_POST['company_name'] !== '' ? trim($_POST['company_name']) : null;
                    $user->ruc = isset($_POST['ruc']) && $_POST['ruc'] !== '' ? trim($_POST['ruc']) : null;
                }
    
                $user->save();

                UserService::syncMirrorData($user, $_SESSION['role'], [
                    'phone' => $phone,
                    'address' => $address,
                ]);
    
                $_SESSION['message'] = "Perfil actualizado con éxito!";
                $_SESSION['message_type'] = "success";
            } catch (Exception $e) {
                $_SESSION['message'] = "Error: " . $e->getMessage();
                $_SESSION['message_type'] = "danger";
            }
    
            header("Location: " . BASE_HEADER . "profile");
            exit;
        }
    }    

    public function updatePassword() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            $currentPassword = $_POST['current_password'];
            $newPassword = $_POST['new_password'];
            $confirmPassword = $_POST['confirm_password'];
    
            if ($newPassword !== $confirmPassword) {
                $_SESSION['message'] = "Las contraseñas no coinciden.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "profile");
                exit;
            }

            $minLength = 8;
            $hasLetter = preg_match('/[a-zA-Z]/', $newPassword);
            $hasNumber = preg_match('/\d/', $newPassword);
            $hasNoSpecial = preg_match('/^[a-zA-Z0-9]+$/', $newPassword);

            if (strlen($newPassword) < $minLength || !$hasLetter || !$hasNumber || !$hasNoSpecial) {
                $_SESSION['message'] = "La nueva contraseña debe tener al menos $minLength caracteres, incluir letras y números, y no debe contener caracteres especiales.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "profile");
                exit;
            }
    
            $userRecord = UserService::getLoggedUser();
    
            if (!password_verify($currentPassword, $userRecord->password)) {
                $_SESSION['message'] = "La contraseña actual es incorrecta.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "profile");
                exit;
            }
    
            $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);

            $userRecord->password = $hashedPassword;
            $userRecord->save();
    
            $_SESSION['message'] = "¡Contraseña actualizada con éxito!";
            $_SESSION['message_type'] = "success";
            header("Location: " . BASE_HEADER . "profile");
            exit;
        }
    }   
    
    public function updatePicture()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['profile_picture'])) {
            
            $userId = $_SESSION['user_id'];
            $file = $_FILES['profile_picture'];
            
            $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
            $newFileName = "user_" . $userId . "." . $ext;
            $uploadPath = __DIR__ . "/../../public/assets/profile/" . $newFileName;
            
            if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                $user = User::find($userId);
                $this->userService->updateProfilePicture($newFileName, $user);
                
                echo json_encode(['success' => true, 'filename' => $newFileName]);
            } else {
                echo json_encode(["success" => false]);
            }
            exit;
        }
    }


}