<?php
/**
 * User Model
 * Handle user data operations
 */

namespace Models;

use Core\DB;

class User {
    private $db;
    
    public function __construct() {
        $this->db = DB::getInstance();
    }
    
    /**
     * Find user by email
     */
    public function findByEmail($email) {
        return $this->db->fetchOne(
            "SELECT * FROM users WHERE email = ? AND active = 1",
            [$email]
        );
    }
    
    /**
     * Find user by ID
     */
    public function findById($id) {
        return $this->db->fetchOne(
            "SELECT * FROM users WHERE id = ? AND active = 1",
            [$id]
        );
    }
    
    /**
     * Create new user
     */
    public function create($userData) {
        $userData['id'] = $this->generateUuid();
        $userData['created_at'] = date('Y-m-d H:i:s');
        
        return $this->db->insert('users', $userData);
    }
    
    /**
     * Update user
     */
    public function update($id, $userData) {
        return $this->db->update('users', $userData, 'id = ?', [$id]);
    }
    
    /**
     * Get user with profile data based on role
     */
    public function getWithProfile($id) {
        $user = $this->findById($id);
        
        if (!$user) {
            return null;
        }
        
        switch ($user['role']) {
            case 'pharmacy':
                $profile = $this->db->fetchOne(
                    "SELECT p.*, w.balance as wallet_balance 
                     FROM pharmacies p 
                     LEFT JOIN wallets w ON w.owner_type = 'PHARMACY' AND w.owner_id = p.id 
                     WHERE p.user_id = ?",
                    [$id]
                );
                $user['pharmacy'] = $profile;
                break;
                
            case 'courier':
                $profile = $this->db->fetchOne(
                    "SELECT c.*, w.balance as wallet_balance 
                     FROM couriers c 
                     LEFT JOIN wallets w ON w.owner_type = 'COURIER' AND w.owner_id = c.id 
                     WHERE c.user_id = ?",
                    [$id]
                );
                $user['courier'] = $profile;
                break;
        }
        
        return $user;
    }
    
    /**
     * Get all users by role
     */
    public function getByRole($role) {
        return $this->db->fetchAll(
            "SELECT * FROM users WHERE role = ? AND active = 1 ORDER BY created_at DESC",
            [$role]
        );
    }
    
    /**
     * Get pending validations (unverified pharmacies/couriers)
     */
    public function getPendingValidations() {
        return $this->db->fetchAll(
            "SELECT u.*, p.verified as pharmacy_verified, p.id as pharmacy_id
             FROM users u
             LEFT JOIN pharmacies p ON u.id = p.user_id
             WHERE u.role IN ('pharmacy', 'courier') 
             AND (u.role = 'pharmacy' AND p.verified = 0 OR u.role = 'courier')
             ORDER BY u.created_at DESC"
        );
    }
    
    /**
     * Validate user (approve pharmacy/courier)
     */
    public function validateUser($id, $approve = true) {
        $user = $this->findById($id);
        
        if (!$user) {
            return false;
        }
        
        $this->db->beginTransaction();
        
        try {
            if ($user['role'] === 'pharmacy') {
                $this->db->update(
                    'pharmacies',
                    ['verified' => $approve ? 1 : 0],
                    'user_id = ?',
                    [$id]
                );
            }
            
            if (!$approve) {
                // Deactivate user if rejected
                $this->db->update('users', ['active' => 0], 'id = ?', [$id]);
            }
            
            $this->db->commit();
            return true;
            
        } catch (\Exception $e) {
            $this->db->rollback();
            throw $e;
        }
    }
    
    /**
     * Generate UUID v4
     */
    private function generateUuid() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
}
?>
