<?php
/**
 * User Model
 * จัดการข้อมูลผู้ใช้งานระบบ
 */

require_once 'config/database.php';

class User {
    private $conn;
    private $table = 'users';
    
    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }
    
    // เข้าสู่ระบบ
    public function login($username, $password) {
        try {
            $sql = "SELECT * FROM {$this->table} WHERE username = :username AND is_active = TRUE";
            $stmt = $this->conn->prepare($sql);
            $stmt->bindValue(':username', $username);
            $stmt->execute();
            
            $user = $stmt->fetch();
            
            if ($user && password_verify($password, $user['password'])) {
                // อัปเดต last_login
                $this->updateLastLogin($user['id']);
                
                // บันทึก log
                $this->logLogin($user['id'], true);
                
                return $user;
            }
            
            // บันทึก log การเข้าสู่ระบบไม่สำเร็จ
            if ($user) {
                $this->logLogin($user['id'], false, 'รหัสผ่านไม่ถูกต้อง');
            }
            
            return false;
            
        } catch (Exception $e) {
            error_log("Login error: " . $e->getMessage());
            return false;
        }
    }
    
    // สร้างผู้ใช้ใหม่
    public function create($data) {
        try {
            $sql = "
                INSERT INTO {$this->table} 
                (username, email, password, full_name, role) 
                VALUES (:username, :email, :password, :full_name, :role)
            ";
            
            $stmt = $this->conn->prepare($sql);
            return $stmt->execute([
                ':username' => $data['username'],
                ':email' => $data['email'],
                ':password' => password_hash($data['password'], PASSWORD_DEFAULT),
                ':full_name' => $data['full_name'],
                ':role' => $data['role'] ?? 'admin'
            ]);
            
        } catch (Exception $e) {
            error_log("Create user error: " . $e->getMessage());
            return false;
        }
    }
    
    // อัปเดตข้อมูลผู้ใช้
    public function update($id, $data) {
        try {
            $sql = "
                UPDATE {$this->table} 
                SET username = :username, email = :email, full_name = :full_name, 
                    role = :role, is_active = :is_active, updated_at = CURRENT_TIMESTAMP
            ";
            
            $params = [
                ':id' => $id,
                ':username' => $data['username'],
                ':email' => $data['email'],
                ':full_name' => $data['full_name'],
                ':role' => $data['role'],
                ':is_active' => $data['is_active'] ?? true
            ];
            
            // อัปเดตรหัสผ่านถ้ามี
            if (!empty($data['password'])) {
                $sql .= ", password = :password";
                $params[':password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            
            $sql .= " WHERE id = :id";
            
            $stmt = $this->conn->prepare($sql);
            return $stmt->execute($params);
            
        } catch (Exception $e) {
            error_log("Update user error: " . $e->getMessage());
            return false;
        }
    }
    
    // เปลี่ยนรหัสผ่าน
    public function changePassword($id, $old_password, $new_password) {
        try {
            // ตรวจสอบรหัสผ่านเก่า
            $sql = "SELECT password FROM {$this->table} WHERE id = :id";
            $stmt = $this->conn->prepare($sql);
            $stmt->bindValue(':id', $id);
            $stmt->execute();
            
            $user = $stmt->fetch();
            
            if (!$user || !password_verify($old_password, $user['password'])) {
                return false;
            }
            
            // อัปเดตรหัสผ่านใหม่
            $sql = "UPDATE {$this->table} SET password = :password WHERE id = :id";
            $stmt = $this->conn->prepare($sql);
            return $stmt->execute([
                ':id' => $id,
                ':password' => password_hash($new_password, PASSWORD_DEFAULT)
            ]);
            
        } catch (Exception $e) {
            error_log("Change password error: " . $e->getMessage());
            return false;
        }
    }
    
    // ดึงข้อมูลผู้ใช้ตาม ID
    public function getById($id) {
        try {
            $sql = "SELECT id, username, email, full_name, role, is_active, last_login, created_at FROM {$this->table} WHERE id = :id";
            $stmt = $this->conn->prepare($sql);
            $stmt->bindValue(':id', $id);
            $stmt->execute();
            
            return $stmt->fetch();
            
        } catch (Exception $e) {
            error_log("Get user by ID error: " . $e->getMessage());
            return false;
        }
    }
    
    // ดึงข้อมูลผู้ใช้ทั้งหมด
    public function getAll() {
        try {
            $sql = "SELECT id, username, email, full_name, role, is_active, last_login, created_at FROM {$this->table} ORDER BY created_at DESC";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute();
            
            return $stmt->fetchAll();
            
        } catch (Exception $e) {
            error_log("Get all users error: " . $e->getMessage());
            return false;
        }
    }
    
    // ลบผู้ใช้
    public function delete($id) {
        try {
            $sql = "UPDATE {$this->table} SET is_active = FALSE WHERE id = :id";
            $stmt = $this->conn->prepare($sql);
            $stmt->bindValue(':id', $id);
            return $stmt->execute();
            
        } catch (Exception $e) {
            error_log("Delete user error: " . $e->getMessage());
            return false;
        }
    }
    
    // ตรวจสอบ username ซ้ำ
    public function isUsernameExists($username, $exclude_id = null) {
        try {
            $sql = "SELECT id FROM {$this->table} WHERE username = :username";
            $params = [':username' => $username];
            
            if ($exclude_id) {
                $sql .= " AND id != :exclude_id";
                $params[':exclude_id'] = $exclude_id;
            }
            
            $stmt = $this->conn->prepare($sql);
            $stmt->execute($params);
            
            return $stmt->fetch() !== false;
            
        } catch (Exception $e) {
            error_log("Check username exists error: " . $e->getMessage());
            return false;
        }
    }
    
    // ตรวจสอบ email ซ้ำ
    public function isEmailExists($email, $exclude_id = null) {
        try {
            $sql = "SELECT id FROM {$this->table} WHERE email = :email";
            $params = [':email' => $email];
            
            if ($exclude_id) {
                $sql .= " AND id != :exclude_id";
                $params[':exclude_id'] = $exclude_id;
            }
            
            $stmt = $this->conn->prepare($sql);
            $stmt->execute($params);
            
            return $stmt->fetch() !== false;
            
        } catch (Exception $e) {
            error_log("Check email exists error: " . $e->getMessage());
            return false;
        }
    }
    
    // อัปเดต last_login
    private function updateLastLogin($id) {
        try {
            $sql = "UPDATE {$this->table} SET last_login = CURRENT_TIMESTAMP WHERE id = :id";
            $stmt = $this->conn->prepare($sql);
            $stmt->bindValue(':id', $id);
            $stmt->execute();
        } catch (Exception $e) {
            error_log("Update last login error: " . $e->getMessage());
        }
    }
    
    // บันทึก log การเข้าสู่ระบบ
    private function logLogin($user_id, $is_successful, $failure_reason = null) {
        try {
            $sql = "
                INSERT INTO login_logs 
                (user_id, ip_address, user_agent, is_successful, failure_reason) 
                VALUES (:user_id, :ip_address, :user_agent, :is_successful, :failure_reason)
            ";
            
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([
                ':user_id' => $user_id,
                ':ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                ':user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
                ':is_successful' => $is_successful,
                ':failure_reason' => $failure_reason
            ]);
        } catch (Exception $e) {
            error_log("Log login error: " . $e->getMessage());
        }
    }
    
    // ดึงประวัติการเข้าสู่ระบบ
    public function getLoginLogs($user_id = null, $limit = 50) {
        try {
            $sql = "
                SELECT ll.*, u.username, u.full_name 
                FROM login_logs ll
                LEFT JOIN {$this->table} u ON ll.user_id = u.id
            ";
            
            $params = [];
            
            if ($user_id) {
                $sql .= " WHERE ll.user_id = :user_id";
                $params[':user_id'] = $user_id;
            }
            
            $sql .= " ORDER BY ll.login_time DESC LIMIT :limit";
            
            $stmt = $this->conn->prepare($sql);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            
            $stmt->execute();
            return $stmt->fetchAll();
            
        } catch (Exception $e) {
            error_log("Get login logs error: " . $e->getMessage());
            return false;
        }
    }
}
?>
