<?php
// src/Models/User.php
namespace App\Models;

use App\Database\DatabaseManager;
use PDO;

class User
{
    private $db;

    public function __construct()
    {
        $this->db = DatabaseManager::connect();
    }

    public function findById(string $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = :id');
        $stmt->bindParam(':id', $id);
        $stmt->execute();

        return $stmt->fetch() ?: null;
    }

    public function findByEmail(string $email): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE email = :email');
        $stmt->bindParam(':email', $email);
        $stmt->execute();

        return $stmt->fetch() ?: null;
    }

    public function create(array $data): string
    {
        $id = bin2hex(random_bytes(16)); // Simple ID generation for demo
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
        
        $stmt = $this->db->prepare('
            INSERT INTO users (id, tenant_id, email, password_hash, first_name, last_name, role, provider, provider_id) 
            VALUES (:id, :tenant_id, :email, :password_hash, :first_name, :last_name, :role, :provider, :provider_id)
            RETURNING id
        ');
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':tenant_id', $data['tenant_id']);
        $stmt->bindParam(':email', $data['email']);
        $stmt->bindParam(':password_hash', $hashedPassword);
        $stmt->bindParam(':first_name', $data['first_name']);
        $stmt->bindParam(':last_name', $data['last_name']);
        $stmt->bindParam(':role', $data['role']);
        $stmt->bindParam(':provider', $data['provider']);
        $stmt->bindParam(':provider_id', $data['provider_id']);
        
        $stmt->execute();
        $result = $stmt->fetch();
        
        return $result['id'];
    }
    
    public function authenticate(string $email, string $password): ?array
    {
        $user = $this->findByEmail($email);
        
        if ($user && password_verify($password, $user['password_hash'])) {
            return $user;
        }
        
        return null;
    }
    
    public function findByProviderId(string $providerId, string $provider): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE provider_id = :provider_id AND provider = :provider');
        $stmt->bindParam(':provider_id', $providerId);
        $stmt->bindParam(':provider', $provider);
        $stmt->execute();

        return $stmt->fetch() ?: null;
    }
}