<?php

namespace App\Models;

use CodeIgniter\Model;
use CodeIgniter\Email\Email;

class UserModel extends Model
{
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'username',
        'email',
        'password',
        'role',
        'otp',
        'otp_expires_at',
        'last_login'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules      = [
        'username' => 'required|min_length[3]|max_length[50]|is_unique[users.username]',
        'email'    => 'required|valid_email|is_unique[users.email]',
        'password' => [
            'rules' => 'required|min_length[12]|regex_match[/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/]',
            'errors' => [
                'required' => 'Password is required',
                'min_length' => 'Password must be at least 12 characters long',
                'regex_match' => 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character'
            ]
        ],
        'role'     => 'required|in_list[admin,superadmin]',
    ];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = ['hashPassword'];
    protected $beforeUpdate   = ['hashPassword'];
    protected $afterUpdate    = ['sendPasswordChangeNotification'];

    /**
     * Hash the password before inserting or updating
     *
     * @param array $data
     * @return array
     */
    protected function hashPassword(array $data)
    {
        if (isset($data['data']['password']) && !empty($data['data']['password'])) {
            $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        }

        return $data;
    }

    /**
     * Send password change notification after update
     *
     * @param array $data
     * @return array
     */
    protected function sendPasswordChangeNotification(array $data)
    {
        // Only send notification if password was updated
        if (isset($data['id']) && !empty($data['id']) && isset($data['data']['password'])) {
            // Get the updated user
            $user = $this->find($data['id']);
            
            if ($user && !empty($user['email'])) {
                // Send email notification
                $email = \Config\Services::email();
                $email->setTo($user['email']);
                $email->setSubject('Password Changed Successfully - Labourdnhdd CMS');
                
                $template = '
                <html>
                <head>
                    <style>
                        body { font-family: Arial, sans-serif; }
                        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                        .header { background: linear-gradient(135deg, #5EC9F8 0%, #3A82D4 50%, #214D8C 100%); color: white; padding: 20px; text-align: center; }
                        .content { background: #f9f9f9; padding: 30px; border: 1px solid #ddd; }
                        .footer { text-align: center; margin-top: 20px; color: #666; font-size: 12px; }
                        .logo { max-width: 150px; margin: 0 auto 20px; }
                    </style>
                </head>
                <body>
                    <div class="container">
                        <div class="header">
                            <img src="cid:labourdnhdd_logo" alt="Labourdnhdd Logo" class="logo">
                            <h1>Labourdnhdd - CMS</h1>
                            <p>Companies Management System</p>
                        </div>
                        <div class="content">
                            <h2>Password Changed Successfully</h2>
                            <p>Hello ' . htmlspecialchars($user['username']) . ',</p>
                            <p>Your password for your Labourdnhdd Companies Management System account has been successfully changed on ' . date('Y-m-d H:i:s') . '.</p>
                            <p>If you did not initiate this change, please <a href="' . base_url('/forgot-password') . '">reset your password</a> immediately.</p>
                            <p>For security reasons, we recommend:</p>
                            <ul>
                                <li>Using a strong, unique password</li>
                                <li>Enabling two-factor authentication if available</li>
                                <li>Regularly updating your passwords</li>
                            </ul>
                            <p>Thank you,<br>The Labourdnhdd Team</p>
                        </div>
                        <div class="footer">
                            <p>This is an automated message. Please do not reply to this email.</p>
                            <p>&copy; ' . date('Y') . ' Labourdnhdd - Companies Management System. All rights reserved.</p>
                        </div>
                    </div>
                </body>
                </html>';

                $email->setMessage($template);
                $email->send();
            }
        }

        return $data;
    }

    /**
     * Find user by username
     *
     * @param string $username
     * @return array|null
     */
    public function findByUsername(string $username)
    {
        return $this->where('username', $username)->first();
    }

    /**
     * Find user by email
     *
     * @param string $email
     * @return array|null
     */
    public function findByEmail(string $email)
    {
        return $this->where('email', $email)->first();
    }

    /**
     * Update user's OTP
     *
     * @param int $userId
     * @param string $otp
     * @param string $expiresAt
     * @return bool
     */
    public function updateOtp(int $userId, string $otp, string $expiresAt)
    {
        return $this->update($userId, [
            'otp' => $otp,
            'otp_expires_at' => $expiresAt
        ]);
    }

    /**
     * Clear user's OTP
     *
     * @param int $userId
     * @return bool
     */
    public function clearOtp(int $userId)
    {
        return $this->update($userId, [
            'otp' => null,
            'otp_expires_at' => null
        ]);
    }

    /**
     * Update user's last login time
     *
     * @param int $userId
     * @return bool
     */
    public function updateLastLogin(int $userId)
    {
        return $this->update($userId, [
            'last_login' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * Update user's password
     *
     * @param int $userId
     * @param string $password
     * @return bool
     */
    public function updatePassword(int $userId, string $password)
    {
        // Temporarily disable callbacks to prevent double hashing
        $this->allowCallbacks = false;
        $result = $this->update($userId, [
            'password' => password_hash($password, PASSWORD_DEFAULT)
        ]);
        // Re-enable callbacks
        $this->allowCallbacks = true;
        
        return $result;
    }
}