<?php
// app/Models/User.php - User Model - UPDATED WITH BANK DETAILS

class User {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create new user
     */
    public function create($data) {
        $sql = "INSERT INTO users (email, password, user_type, email_verified, created_at) 
                VALUES (?, ?, ?, ?, NOW())";
        
        $result = $this->db->execute($sql, [
            $data['email'],
            $data['password'],
            $data['user_type'],
            $data['email_verified'] ?? 0
        ]);
        
        return $result ? $this->db->lastInsertId() : false;
    }
    
    /**
     * Find user by ID
     */
    public function find($id) {
        $sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
        return $this->db->fetch($sql, [$id]);
    }
    
    /**
     * Find user by email
     */
    public function findByEmail($email) {
        $sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
        return $this->db->fetch($sql, [$email]);
    }
    
    /**
     * Verify password - ADDED
     */
    public function verifyPassword($user_id, $password) {
        $user = $this->find($user_id);
        if (!$user) {
            return false;
        }
        
        return password_verify($password, $user['password']);
    }
    
    /**
     * Find user by reset token
     */
    public function findByResetToken($token) {
        $sql = "SELECT * FROM users 
                WHERE reset_token = ? 
                AND reset_token_expires > NOW()
                LIMIT 1";
        return $this->db->fetch($sql, [$token]);
    }
    
    /**
     * Find user by verification token
     */
    public function findByVerificationToken($token) {
        $sql = "SELECT * FROM users 
                WHERE email_verification_token = ?
                LIMIT 1";
        return $this->db->fetch($sql, [$token]);
    }
    
    /**
     * Get all users with pagination
     */
    public function getAll($limit = 20, $offset = 0, $filters = []) {
        $sql = "SELECT u.*, 
                CASE 
                    WHEN u.user_type = 'vendor' THEN v.business_name
                    WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                    ELSE 'Admin'
                END as display_name
                FROM users u
                LEFT JOIN vendors v ON u.id = v.user_id
                LEFT JOIN customers c ON u.id = c.user_id
                WHERE 1=1";
        
        $params = [];
        
        if (!empty($filters['user_type'])) {
            $sql .= " AND u.user_type = ?";
            $params[] = $filters['user_type'];
        }
        
        if (!empty($filters['status'])) {
            $sql .= " AND u.status = ?";
            $params[] = $filters['status'];
        }
        
        if (!empty($filters['search'])) {
            $sql .= " AND (u.email LIKE ? OR v.business_name LIKE ? OR CONCAT(c.first_name, ' ', c.last_name) LIKE ?)";
            $search = '%' . $filters['search'] . '%';
            $params[] = $search;
            $params[] = $search;
            $params[] = $search;
        }
        
        $sql .= " ORDER BY u.created_at DESC LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = $offset;
        
        return $this->db->fetchAll($sql, $params);
    }
    
    /**
     * Count users
     */
    public function count($filters = []) {
        $sql = "SELECT COUNT(*) as count FROM users u WHERE 1=1";
        $params = [];
        
        if (!empty($filters['user_type'])) {
            $sql .= " AND u.user_type = ?";
            $params[] = $filters['user_type'];
        }
        
        if (!empty($filters['status'])) {
            $sql .= " AND u.status = ?";
            $params[] = $filters['status'];
        }
        
        $result = $this->db->fetch($sql, $params);
        return $result['count'] ?? 0;
    }
    
    /**
     * Update user
     */
    public function update($id, $data) {
        $fields = [];
        $params = [];
        
        foreach ($data as $key => $value) {
            $fields[] = "{$key} = ?";
            $params[] = $value;
        }
        
        $params[] = $id;
        
        $sql = "UPDATE users SET " . implode(', ', $fields) . ", updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, $params);
    }
    
    /**
     * Update password
     */
    public function updatePassword($user_id, $new_password) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $sql = "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$hashed_password, $user_id]);
    }
    
    /**
     * Update bank details - ADDED
     */
    public function updateBankDetails($user_id, $bank_data) {
        $sql = "UPDATE users SET 
                bank_name = ?,
                account_name = ?,
                account_number = ?,
                updated_at = NOW() 
                WHERE id = ?";
        
        return $this->db->execute($sql, [
            $bank_data['bank_name'] ?? null,
            $bank_data['account_name'] ?? null,
            $bank_data['account_number'] ?? null,
            $user_id
        ]);
    }
    
    /**
     * Get bank details - ADDED
     */
    public function getBankDetails($user_id) {
        $sql = "SELECT bank_name, account_name, account_number FROM users WHERE id = ? LIMIT 1";
        return $this->db->fetch($sql, [$user_id]);
    }
    
    /**
     * Update status
     */
    public function updateStatus($id, $status) {
        $sql = "UPDATE users SET status = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$status, $id]);
    }
    
    /**
     * Verify email
     */
    public function verifyEmail($id) {
        $sql = "UPDATE users SET email_verified = 1, email_verification_token = NULL, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$id]);
    }
    
    /**
     * Set verification token
     */
    public function setVerificationToken($id, $token) {
        $sql = "UPDATE users SET email_verification_token = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$token, $id]);
    }
    
    /**
     * Set reset token
     */
    public function setResetToken($id, $token, $expires) {
        $sql = "UPDATE users SET reset_token = ?, reset_token_expires = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$token, $expires, $id]);
    }
    
    /**
     * Clear reset token
     */
    public function clearResetToken($id) {
        $sql = "UPDATE users SET reset_token = NULL, reset_token_expires = NULL, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$id]);
    }
    
    /**
     * Update last login
     */
    public function updateLastLogin($id) {
        $sql = "UPDATE users SET last_login = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$id]);
    }
    
    /**
     * Delete user
     */
    public function delete($id) {
        $sql = "DELETE FROM users WHERE id = ?";
        return $this->db->execute($sql, [$id]);
    }
    
    /**
     * Check if email exists
     */
    public function emailExists($email, $exclude_id = null) {
        if ($exclude_id) {
            $sql = "SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1";
            $result = $this->db->fetch($sql, [$email, $exclude_id]);
        } else {
            $sql = "SELECT id FROM users WHERE email = ? LIMIT 1";
            $result = $this->db->fetch($sql, [$email]);
        }
        
        return $result !== null;
    }
    
    /**
     * Get user statistics
     */
    public function getStats() {
        $sql = "SELECT 
                COUNT(*) as total_users,
                SUM(CASE WHEN user_type = 'vendor' THEN 1 ELSE 0 END) as total_vendors,
                SUM(CASE WHEN user_type = 'customer' THEN 1 ELSE 0 END) as total_customers,
                SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_users,
                SUM(CASE WHEN DATE(created_at) >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as new_this_week,
                SUM(CASE WHEN DATE(created_at) >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as new_this_month
                FROM users";
        
        return $this->db->fetch($sql);
    }
    
    /**
     * Get recently registered users
     */
    public function getRecent($limit = 10) {
        $sql = "SELECT u.*, 
                CASE 
                    WHEN u.user_type = 'vendor' THEN v.business_name
                    WHEN u.user_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                    ELSE 'Admin'
                END as display_name
                FROM users u
                LEFT JOIN vendors v ON u.id = v.user_id
                LEFT JOIN customers c ON u.id = c.user_id
                ORDER BY u.created_at DESC
                LIMIT ?";
        
        return $this->db->fetchAll($sql, [$limit]);
    }
}