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

class Project_model extends CI_Model {
    
    public function __construct() {
       log_message('info', 'Project Model Class Initialized');
    }
    
    // --- SETTINGS MANAGEMENT ---
    public function get_setting($key) {
        // Ensure table exists first (lazy check)
        $this->db->query("CREATE TABLE IF NOT EXISTS homepage_settings (setting_key VARCHAR(50) PRIMARY KEY, setting_value TEXT)");
        
        $this->db->where('setting_key', $key);
        $row = $this->db->get('homepage_settings')->row();
        return $row ? $row->setting_value : null;
    }

    public function save_setting($key, $value) {
        $this->db->query("CREATE TABLE IF NOT EXISTS homepage_settings (setting_key VARCHAR(50) PRIMARY KEY, setting_value TEXT)");
        
        // Check if exists
        $this->db->where('setting_key', $key);
        if ($this->db->count_all_results('homepage_settings') > 0) {
            $this->db->where('setting_key', $key);
            return $this->db->update('homepage_settings', ['setting_value' => $value]);
        } else {
            return $this->db->insert('homepage_settings', [
                'setting_key' => $key,
                'setting_value' => $value
            ]);
        }
    }
    
    public function get_all_projects() {
        $this->db->select('projects.*');
        // Fallback media (First image in gallery) - renaming to avoid conflict
        $this->db->select('(SELECT media_path FROM project_media WHERE project_media.project_id = projects.id ORDER BY display_order ASC LIMIT 1) as fallback_media');
        $this->db->select('(SELECT media_type FROM project_media WHERE project_media.project_id = projects.id ORDER BY display_order ASC LIMIT 1) as fallback_type');
        
        // Selected Thumbnail (Flagged in Media Table)
        $this->db->select('(SELECT media_path FROM project_media WHERE project_media.project_id = projects.id AND is_thumbnail = 1 LIMIT 1) as selected_thumb');
        $this->db->select('(SELECT media_type FROM project_media WHERE project_media.project_id = projects.id AND is_thumbnail = 1 LIMIT 1) as selected_thumb_type');

        $this->db->from('projects');
        $this->db->order_by('projects.display_order', 'ASC');
        $this->db->order_by('projects.created_at', 'DESC');
        return $this->db->get()->result();
    }
    
    public function get_featured_projects() {
        $this->db->where('is_featured', 1);
        $this->db->order_by('display_order', 'ASC');
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('projects')->result();
    }
    
    public function get_project($id) {
        $this->db->where('id', $id);
        $query = $this->db->get('projects');
        return $query->row();
    }
    
    public function create_project($data) {
        if (!$this->session->userdata('admin_username')) {
            $data['created_by'] = 'admin'; // Fallback
        } else {
            $data['created_by'] = $this->session->userdata('admin_username');
        }
        $this->db->insert('projects', $data);
        return $this->db->insert_id();
    }
    
    public function update_project($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('projects', $data);
    }
    
    public function delete_project($id) {
        // Delete associated media files first
        $project_media = $this->get_project_media($id);
        foreach ($project_media as $media) {
            if (file_exists(FCPATH . $media->media_path)) {
                unlink(FCPATH . $media->media_path);
            }
            if (!empty($media->thumbnail_path) && file_exists(FCPATH . $media->thumbnail_path)) {
                unlink(FCPATH . $media->thumbnail_path);
            }
        }
        
        // Delete media records
        $this->db->where('project_id', $id);
        $this->db->delete('project_media');
        
        // Then delete project
        $this->db->where('id', $id);
        return $this->db->delete('projects');
    }
    
    // Project Media Methods
    public function get_project_media($project_id) {
        $this->db->where('project_id', $project_id);
        $this->db->order_by('display_order', 'ASC');
        return $this->db->get('project_media')->result();
    }
    
    public function get_project_thumbnail($project_id) {
        $this->db->where('project_id', $project_id);
        $this->db->where('is_thumbnail', 1);
        $query = $this->db->get('project_media');
        return $query->row();
    }
    
    public function add_project_media($data) {
        return $this->db->insert('project_media', $data);
    }
    
    public function update_project_media($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('project_media', $data);
    }
    
    public function delete_project_media($id) {
        $media = $this->db->where('id', $id)->get('project_media')->row();
        if ($media) {
            if (file_exists(FCPATH . $media->media_path)) {
                unlink(FCPATH . $media->media_path);
            }
            if (!empty($media->thumbnail_path) && file_exists(FCPATH . $media->thumbnail_path)) {
                unlink(FCPATH . $media->thumbnail_path);
            }
        }
        
        $this->db->where('id', $id);
        return $this->db->delete('project_media');
    }
    
    public function set_project_thumbnail($project_id, $media_id) {
        // Remove thumbnail flag from all media
        $this->db->where('project_id', $project_id);
        $this->db->update('project_media', ['is_thumbnail' => 0]);
        
        // Set new thumbnail
        $this->db->where('id', $media_id);
        $this->db->where('project_id', $project_id);
        return $this->db->update('project_media', ['is_thumbnail' => 1]);
    }
    
    public function update_media_order($project_id, $order_data) {
        foreach ($order_data as $media_id => $order) {
            $this->db->where('id', $media_id);
            $this->db->where('project_id', $project_id);
            $this->db->update('project_media', ['display_order' => $order]);
        }
        return true;
    }

    public function update_project_display_order($order_data) {
        foreach ($order_data as $project) {
            $data = ['display_order' => $project['order']];
            
            if (isset($project['size'])) {
                $data['project_size'] = $project['size'];
            }
            
            $this->db->where('id', $project['id']);
            $this->db->update('projects', $data);
        }
        return true;
    }
}
?>