<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pdf_model extends CI_Model {

    public function __construct() {
      log_message('info', 'Pdf_model initialized');
    }

    public function create_directories() {
        $directories = array(
            'assets/uploads/tmp',
            'assets/uploads/images',
            'assets/uploads/pdfs'
        );

        foreach ($directories as $dir) {
            if (!is_dir(FCPATH . $dir)) {
                mkdir(FCPATH . $dir, 0755, TRUE);
            }
        }
    }

    public function create_pdf_record($upload_data) {
        $data = array(
            'original_name' => $upload_data['orig_name'],
            'filename' => $upload_data['file_name'],
            'file_size' => $upload_data['file_size'],
            'uploaded_at' => date('Y-m-d H:i:s'),
            'status' => 'pending'
        );

        $this->db->insert('pdf_records', $data);
        return $this->db->insert_id();
    }

    public function get_record($record_id) {
        return $this->db->get_where('pdf_records', array('id' => $record_id))->row();
    }

    public function get_record_with_results($record_id) {
        return $this->db->get_where('pdf_records', array('id' => $record_id))->row();
    }

    public function get_all_records() {
        $this->db->order_by('uploaded_at', 'DESC');
        return $this->db->get('pdf_records')->result();
    }

    public function update_record($record_id, $data) {
        $this->db->where('id', $record_id);
        return $this->db->update('pdf_records', $data);
    }

    public function get_processing_stats() {
        $stats = array(
            'total' => 0,
            'pending' => 0,
            'done' => 0,
            'error' => 0
        );

        $this->db->select('status, COUNT(*) as count');
        $this->db->group_by('status');
        $results = $this->db->get('pdf_records')->result();

        foreach ($results as $result) {
            $stats[$result->status] = $result->count;
            $stats['total'] += $result->count;
        }

        return $stats;
    }

    public function get_pending_count() {
        $this->db->where('status', 'pending');
        return $this->db->count_all_results('pdf_records');
    }
}