<?php

class Lead extends Model{
    
    public function addLead($data) {
        $stmt = $this->db->prepare("
            INSERT INTO leads (user_id, name, email, phone, source, created_at)
            VALUES (:user_id, :name, :email, :phone, :source, NOW())
        ");

        return $stmt->execute([
             'user_id' => $data['user_id'],
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'source' => $data['source']
        ]);
    }
    
    public function getAllLeads($userId, $role) {
        if ($role === 'admin') {
            $stmt = $this->db->query("
                SELECT * FROM leads
            ");
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $stmt = $this->db->prepare("
                SELECT * FROM leads WHERE user_id = ?
            ");
            $stmt->execute([$userId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
    
    public function getLeadsPaginated($userId, $role, $limit, $offset){
    if (strtolower($role) === 'admin') {
        $stmt = $this->db->prepare("
            SELECT * FROM leads
            LIMIT :limit OFFSET :offset
        ");
    } else {
        $stmt = $this->db->prepare("
            SELECT * FROM leads
            WHERE user_id = :user_id
            LIMIT :limit OFFSET :offset
        ");
        $stmt->bindValue(':user_id', $userId, PDO::PARAM_INT);
    }

    $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

    public function countLeads($userId, $role){
    if (strtolower($role) === 'admin') {
        $stmt = $this->db->query("SELECT COUNT(*) FROM leads");
    } else {
        $stmt = $this->db->prepare("SELECT COUNT(*) FROM leads WHERE user_id = ?");
        $stmt->execute([$userId]);
    }
    return $stmt->fetchColumn();
}

    public function updateLead($id, $data) {
        $stmt = $this->db->prepare("UPDATE leads SET name = ?, email = ?, phone = ?, source = ? WHERE id = ?");
        return $stmt->execute([
            $data['name'],
            $data['email'],
            $data['phone'],
            $data['source'],
            $id
        ]);
    }
    
    public function getLeadById($id) {
        $stmt = $this->db->prepare("SELECT * FROM leads WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    public function deleteLead($id){
        $stmt = $this->db->prepare("DELETE FROM leads WHERE id = ?");
        return $stmt->execute([$id]);
    }


}
