<?php
namespace App\Models;

use App\Core\Model;

class UploadedDocument extends Model {
    protected $table = 'uploaded_documents';
    protected $primaryKey = 'id';
    protected $fillable = [
        'person_id', 'document_type', 'file_name', 'file_path', 
        'file_size', 'mime_type', 'uploaded_by'
    ];
    
    /**
     * Get documents by person
     */
    public function getByPerson($person_id) {
        $stmt = $this->db->prepare("
            SELECT * FROM {$this->table} 
            WHERE person_id = ? AND deleted_at IS NULL
            ORDER BY created_at DESC
        ");
        $stmt->execute([$person_id]);
        return $this->processResults($stmt->fetchAll());
    }
    
    /**
     * Get document by type
     */
    public function getByType($person_id, $type) {
        $stmt = $this->db->prepare("
            SELECT * FROM {$this->table} 
            WHERE person_id = ? AND document_type = ? AND deleted_at IS NULL
            ORDER BY created_at DESC
        ");
        $stmt->execute([$person_id, $type]);
        return $this->processResults($stmt->fetchAll());
    }
    
    /**
     * Soft delete document
     */
    public function delete($id) {
        $doc = $this->find($id);
        if ($doc) {
            // Delete physical file
            $filePath = BASE_PATH . $doc['file_path'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }
        
        return parent::delete($id);
    }
    
    /**
     * Get total storage used by user
     */
    public function getStorageUsed($user_id) {
        $stmt = $this->db->prepare("
            SELECT SUM(file_size) as total 
            FROM {$this->table} 
            WHERE uploaded_by = ? AND deleted_at IS NULL
        ");
        $stmt->execute([$user_id]);
        $result = $stmt->fetch();
        return $result['total'] ?? 0;
    }
}