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

use App\Database\DatabaseManager;
use PDO;

class JobPosition
{
    private $db;

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

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

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

    public function findByTenant(string $tenantId, string $status = 'published'): array
    {
        $stmt = $this->db->prepare('SELECT * FROM job_positions WHERE tenant_id = :tenant_id AND status = :status ORDER BY created_at DESC');
        $stmt->bindParam(':tenant_id', $tenantId);
        $stmt->bindParam(':status', $status);
        $stmt->execute();

        return $stmt->fetchAll();
    }

    public function create(array $data): string
    {
        $id = bin2hex(random_bytes(16)); // Simple ID generation for demo
        
        $stmt = $this->db->prepare('
            INSERT INTO job_positions (id, tenant_id, title, description, location, employment_type, salary_min, salary_max, posted_by, status) 
            VALUES (:id, :tenant_id, :title, :description, :location, :employment_type, :salary_min, :salary_max, :posted_by, :status)
            RETURNING id
        ');
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':tenant_id', $data['tenant_id']);
        $stmt->bindParam(':title', $data['title']);
        $stmt->bindParam(':description', $data['description']);
        $stmt->bindParam(':location', $data['location']);
        $stmt->bindParam(':employment_type', $data['employment_type']);
        $stmt->bindParam(':salary_min', $data['salary_min']);
        $stmt->bindParam(':salary_max', $data['salary_max']);
        $stmt->bindParam(':posted_by', $data['posted_by']);
        $stmt->bindParam(':status', $data['status']);
        
        $stmt->execute();
        $result = $stmt->fetch();
        
        return $result['id'];
    }
    
    public function updateStatus(string $id, string $status, string $tenantId): bool
    {
        $stmt = $this->db->prepare('UPDATE job_positions SET status = :status, updated_at = CURRENT_TIMESTAMP WHERE id = :id AND tenant_id = :tenant_id');
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':status', $status);
        $stmt->bindParam(':tenant_id', $tenantId);
        
        return $stmt->execute();
    }
}