<?php
class Admin extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('Project_model');
        $this->load->model('Client_model');
        $this->load->model('Contact_model');
        $this->load->model('Admin_model');
        $this->load->model('About_model'); // Add this line
        $this->load->library('form_validation');
        $this->load->helper('url');
        $this->load->library('upload');
        $this->load->library('session');
    }
    
    private function check_login() {
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }
    }
    
    public function login() {
        if ($this->session->userdata('admin_logged_in')) {
            redirect('admin/dashboard');
        }
        
        if ($this->input->post()) {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            
            $admin = $this->Admin_model->validate_admin($username, $password);
            
            if ($admin) {
                $this->session->set_userdata('admin_logged_in', true);
                $this->session->set_userdata('admin_username', $admin->username);
                redirect('admin/dashboard');
            } else {
                $data['error'] = 'Invalid username or password';
            }
        }
        
        $this->load->view('admin/login');
    }
    
    public function logout() {
        $this->session->unset_userdata('admin_logged_in');
        $this->session->unset_userdata('admin_username');
        $this->session->sess_destroy();
        redirect('admin/login');
    }
    
    public function dashboard() {
        $this->check_login();
        
        $data['total_projects'] = $this->db->count_all('projects');
        $data['total_clients'] = $this->db->count_all('clients');
        $data['total_inquiries'] = $this->db->count_all('contact_inquiries');
        $data['total_views'] = $this->db->count_all('projects');
        $data['recent_inquiries'] = $this->Contact_model->get_all_inquiries();
        
        $this->load->view('admin/dashboard', $data);
    }
    
    public function projects() {
        $this->check_login();
        
        $data['projects'] = $this->Project_model->get_all_projects();
        
        $this->load->view('admin/header');
        $this->load->view('admin/projects', $data);
        $this->load->view('admin/footer');
    }
    
    public function add_project() {
        $this->check_login();
        
        if ($this->input->post()) {
            $config['upload_path'] = './uploads/images/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif|webp|mp4|mov|avi';
            $config['max_size'] = 50000;
            $config['encrypt_name'] = TRUE;
            
            $this->upload->initialize($config);
            
            if ($this->upload->do_upload('media_file')) {
                $upload_data = $this->upload->data();
                
                // Determine media type
                $image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
                $video_extensions = ['.mp4', '.mov', '.avi'];
                $file_extension = strtolower($upload_data['file_ext']);
                
                $media_type = in_array($file_extension, $video_extensions) ? 'video' : 'image';
                
                $project_data = array(
                    'title' => $this->input->post('title'),
                    'client_name' => $this->input->post('client_name'),
                    'model_name' => $this->input->post('model_name'),
                    'description' => $this->input->post('description'),
                    'media_type' => $media_type,
                    'media_path' => 'uploads/images/' . $upload_data['file_name'],
                    'project_size' => $this->input->post('project_size'),
                    'display_order' => $this->input->post('display_order') ?: 0
                );
                
                if ($this->Project_model->create_project($project_data)) {
                    $this->session->set_flashdata('success', 'Project added successfully!');
                } else {
                    $this->session->set_flashdata('error', 'Error adding project. Please try again.');
                }
            } else {
                $this->session->set_flashdata('error', $this->upload->display_errors());
            }
            redirect('admin/projects');
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/add_project');
        $this->load->view('admin/footer');
    }



    public function test_debug() {
    echo "DEBUG MODE<br>";
    echo "Session logged in: " . ($this->session->userdata('admin_logged_in') ? 'YES' : 'NO') . "<br>";
    echo "Is POST: " . ($this->input->server('REQUEST_METHOD') === 'POST' ? 'YES' : 'NO') . "<br>";
    echo "Base URL: " . base_url() . "<br>";
    echo "Current URL: " . current_url() . "<br>";
    
    // Test JSON output
    echo "<hr>Testing JSON output:<br>";
    $this->output->set_content_type('application/json');
    echo json_encode(['test' => 'success', 'time' => date('Y-m-d H:i:s')]);
}
    public function add_wizard() {
    // Increase limits for large uploads
    set_time_limit(0);
    ini_set('memory_limit', '512M');

    // First, check if this is a POST request
    if ($this->input->server('REQUEST_METHOD') !== 'POST') {
        // Load the wizard view for GET requests
        
        $data['clients'] = $this->Client_model->get_all_clients();
        $this->load->view('admin/header');
        $this->load->view('admin/add_project_wizard', $data);
        $this->load->view('admin/footer');
      
        return;
    }
    
    // Now handle POST request
    ob_clean(); // Clean any previous output (HTML errors/warnings)
    $this->output->set_content_type('application/json');
    
    // Check if POST is empty but we have content length - indicates post_max_size exceeded
    if (empty($_POST) && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
        $max_size = ini_get('post_max_size');
        throw new Exception("File too large. Server limit is $max_size. Please try smaller files.");
    }

    try {
        // Check login FIRST
        if (!$this->session->userdata('admin_logged_in')) {
            throw new Exception('Session expired. Please login again.');
        }
        
        // Validate basic info
        $title = $this->input->post('title', true);
        $client_name = $this->input->post('client_name', true);
        $project_size = $this->input->post('project_size', true);
        
        if (empty($title) || empty($client_name) || empty($project_size)) {
            error_log('Missing fields - Title: ' . $title . ', Client: ' . $client_name . ', Size: ' . $project_size);
            throw new Exception('Please fill in all required fields');
        }
        
        // Debug: Log what we received
        error_log('=== ADD WIZARD DEBUG ===');
        error_log('Title: ' . $title);
        error_log('Client: ' . $client_name);
        error_log('Files count: ' . (isset($_FILES['media_files']) ? count($_FILES['media_files']['name']) : 0));
        
        // Prepare project data
        $project_data = array(
            'title' => $title,
            'client_name' => $client_name,
            'model_name' => $this->input->post('model_name', true),
            'description' => $this->input->post('description', true),
            'shoot_date' => $this->input->post('shoot_date'),
            'project_size' => $project_size,
            'display_order' => $this->input->post('display_order') ?: 0,
            'is_featured' => $this->input->post('is_featured') ? 1 : 0,
            'created_by' => $this->session->userdata('admin_username'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        );
        
        // Create project
        $this->db->insert('projects', $project_data);
        $project_id = $this->db->insert_id();
        
        if (!$project_id) {
            $error = $this->db->error();
            throw new Exception('Database error: ' . $error['message']);
        }
        
        error_log('Project created with ID: ' . $project_id);
        
        // Ensure is_thumbnail column exists directly here to avoid external CLI issues
        $this->db->query("ALTER TABLE project_media ADD COLUMN IF NOT EXISTS is_thumbnail TINYINT DEFAULT 0");

        // Handle media uploads
        if (isset($_FILES['media_files']) && !empty($_FILES['media_files']['name'][0])) {
            $upload_path = FCPATH . 'uploads/projects/';
            
            // Create directory if it doesn't exist
            if (!is_dir($upload_path)) {
                mkdir($upload_path, 0777, true);
            }
            
            $files = $_FILES['media_files'];
            $file_count = count($files['name']);
            
            for ($i = 0; $i < $file_count; $i++) {
                if ($files['error'][$i] !== UPLOAD_ERR_OK) {
                    error_log('File upload error for ' . $files['name'][$i] . ': ' . $files['error'][$i]);
                    continue;
                }
                
                $temp_file = $files['tmp_name'][$i];
                $file_name = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $files['name'][$i]);
                $destination = $upload_path . $file_name;
                
                // Move uploaded file
                if (move_uploaded_file($temp_file, $destination)) {
                    // Determine media type with safer fallback
                    $file_type = 'application/octet-stream';
                    if (function_exists('mime_content_type')) {
                        $file_type = mime_content_type($destination);
                    } elseif (function_exists('finfo_open')) {
                        $finfo = finfo_open(FILEINFO_MIME_TYPE);
                        $file_type = finfo_file($finfo, $destination);
                        finfo_close($finfo);
                    } else {
                        // Fallback to extension check
                        $ext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
                        if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) $file_type = 'image/' . $ext;
                        elseif (in_array($ext, ['mp4','mov','avi'])) $file_type = 'video/' . $ext;
                    }

                    $media_type = strpos($file_type, 'video') !== false ? 'video' : 'image';
                    
                    $media_data = array(
                        'project_id' => $project_id,
                        'media_type' => $media_type,
                        'media_path' => 'uploads/projects/' . $file_name,
                        'display_order' => $i,
                        'created_at' => date('Y-m-d H:i:s')
                    );

                    // Check if this is the selected thumbnail
                    $thumb_index = $this->input->post('thumbnail_index');
                    if ($thumb_index !== null && $i == $thumb_index) {
                        $media_data['is_thumbnail'] = 1;
                    } else {
                        $media_data['is_thumbnail'] = 0;
                    }
                    
                    if (!$this->db->insert('project_media', $media_data)) {
                         $db_err = $this->db->error();
                         error_log('DB Error (project_media): ' . json_encode($db_err));
                         // Don't crash the whole loop, but log it.
                    }
                    
                    error_log('File saved: ' . $file_name);
                } else {
                    error_log('Failed to move file: ' . $files['name'][$i]);
                }
            }
        }
        
        // Return success
        echo json_encode([
            'success' => true,
            'message' => 'Project created successfully',
            'project_id' => $project_id
        ]);
        
    } catch (Throwable $e) {
        error_log('Exception/Error in add_wizard: ' . $e->getMessage());
        
        // Ensure we clear any previous output carefully
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        // Return simple JSON error
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'error' => 'Server Error: ' . $e->getMessage()
        ]);
        exit; // Stop execution immediately
    }
}
    
    public function clients() {
        $this->check_login();
        
        $data['clients'] = $this->Client_model->get_all_clients();
        
        $this->load->view('admin/header');
        $this->load->view('admin/clients', $data);
        $this->load->view('admin/footer');
    }
    
    public function add_client() {
        $this->check_login();
        
        if ($this->input->post()) {
            $config['upload_path'] = FCPATH . 'uploads/clients/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif|webp';
            $config['max_size'] = 2048;
            $config['encrypt_name'] = TRUE;
            $config['max_width'] = 2000;
            $config['max_height'] = 2000;
            
            if (!is_dir($config['upload_path'])) {
                mkdir($config['upload_path'], 0755, true);
            }
            
            $this->upload->initialize($config);
            
            $logo_path = null;
            if (!empty($_FILES['logo']['name'])) {
                if ($this->upload->do_upload('logo')) {
                    $upload_data = $this->upload->data();
                    $logo_path = 'uploads/clients/' . $upload_data['file_name'];
                } else {
                    $error = $this->upload->display_errors();
                    $this->session->set_flashdata('error', $error);
                    redirect('admin/clients/add');
                }
            }
            
            $client_data = array(
                'name' => $this->input->post('name'),
                'website' => $this->input->post('website'),
                'display_order' => $this->input->post('display_order') ?: 0
            );
            
            if ($logo_path) {
                $client_data['logo'] = $logo_path;
            }
            
            if ($this->Client_model->create_client($client_data)) {
                $this->session->set_flashdata('success', 'Client added successfully!');
            } else {
                $this->session->set_flashdata('error', 'Error adding client. Please try again.');
            }
            redirect('admin/clients');
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/add_client');
        $this->load->view('admin/footer');
    }
    
    public function view_client($id) {
        $this->check_login();
        
        $data['client'] = $this->Client_model->get_client($id);
        if (!$data['client']) {
            show_404();
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/view_client', $data);
        $this->load->view('admin/footer');
    }
    
    public function edit_client($id) {
        $this->check_login();
        
        $data['client'] = $this->Client_model->get_client($id);
        if (!$data['client']) {
            show_404();
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/edit_client', $data);
        $this->load->view('admin/footer');
    }
    
    public function update_client($id) {
        $this->check_login();
        
        $client = $this->Client_model->get_client($id);
        if (!$client) {
            show_404();
        }
        
        if ($this->input->post()) {
            $config['upload_path'] = FCPATH . 'uploads/clients/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif|webp';
            $config['max_size'] = 2048;
            $config['encrypt_name'] = TRUE;
            
            if (!is_dir($config['upload_path'])) {
                mkdir($config['upload_path'], 0755, true);
            }
            
            $this->upload->initialize($config);
            
            $logo_path = $client->logo;
            
            if ($this->input->post('remove_logo') && $client->logo && file_exists(FCPATH . $client->logo)) {
                unlink(FCPATH . $client->logo);
                $logo_path = null;
            }
            
            if (!empty($_FILES['logo']['name'])) {
                if ($this->upload->do_upload('logo')) {
                    if ($client->logo && file_exists(FCPATH . $client->logo)) {
                        unlink(FCPATH . $client->logo);
                    }
                    
                    $upload_data = $this->upload->data();
                    $logo_path = 'uploads/clients/' . $upload_data['file_name'];
                } else {
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect('admin/clients/edit/' . $id);
                }
            }
            
            $client_data = array(
                'name' => $this->input->post('name'),
                'website' => $this->input->post('website'),
                'display_order' => $this->input->post('display_order') ?: 0
            );
            
            if ($logo_path !== $client->logo) {
                $client_data['logo'] = $logo_path;
            }
            
            if ($this->Client_model->update_client($id, $client_data)) {
                $this->session->set_flashdata('success', 'Client updated successfully!');
            } else {
                $this->session->set_flashdata('error', 'Error updating client. Please try again.');
            }
            redirect('admin/clients');
        }
    }
    

    
 
    public function delete_client($id) {
        $this->check_login();
        
        $client = $this->Client_model->get_client($id);
        if ($client && $client->logo && file_exists($client->logo)) {
            unlink($client->logo);
        }
        
        if ($this->Client_model->delete_client($id)) {
            $this->session->set_flashdata('success', 'Client deleted successfully!');
        } else {
            $this->session->set_flashdata('error', 'Error deleting client. Please try again.');
        }
        redirect('admin/clients');
    }
    
    public function delete_project($id) {
        $this->check_login();
        
        // Fetch project to delete files
        $project = $this->Project_model->get_project($id);
        
        if ($project) {
            // Delete Thumbnail
            if (!empty($project->thumbnail_path) && file_exists(FCPATH . $project->thumbnail_path)) {
                @unlink(FCPATH . $project->thumbnail_path);
            }
            
            // Delete Gallery Media
            $media_list = $this->Project_model->get_project_media($id);
            if ($media_list) {
                foreach ($media_list as $media) {
                    if (!empty($media->media_path) && file_exists(FCPATH . $media->media_path)) {
                        @unlink(FCPATH . $media->media_path);
                    }
                }
            }
        }
        
        if ($this->Project_model->delete_project($id)) {
            $this->session->set_flashdata('success', 'Project and files deleted successfully!');
        } else {
            $this->session->set_flashdata('error', 'Error deleting project. Please try again.');
        }
        redirect('admin/projects');
    }
    
    public function contact_inquiries() {
        $this->check_login();
        
        $data['inquiries'] = $this->Contact_model->get_all_inquiries();
        
        $this->load->view('admin/header');
        $this->load->view('admin/contact_inquiries', $data);
        $this->load->view('admin/footer');
    }
    
    public function view_inquiry($id) {
        $this->check_login();
        
        // Add get_inquiry method to Contact_model if not exists, or direct query
        $data['inquiry'] = $this->db->where('id', $id)->get('contact_inquiries')->row();
        
        if (!$data['inquiry']) {
            show_404();
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/view_inquiry', $data);
        $this->load->view('admin/footer');
    }
    
    // About Us Management
    public function about() {
        $this->check_login();
        
        $data['about_sections'] = $this->About_model->get_all_about_sections();
        
        $this->load->view('admin/header');
        $this->load->view('admin/about', $data);
        $this->load->view('admin/footer');
    }
    
    public function edit_about($id = 1) {
        $this->check_login();
        
        $data['about'] = $this->About_model->get_about_by_id($id);
        
        if (!$data['about']) {
            show_404();
        }
        
        if ($this->input->post()) {
            $about_data = array(
                'title' => $this->input->post('title'),
                'content' => $this->input->post('content'),
                'quote' => $this->input->post('quote'),
                'display_order' => $this->input->post('display_order') ?: 0,
                'updated_at' => date('Y-m-d H:i:s')
            );
            
            if (!empty($_FILES['image']['name'])) {
                $config['upload_path'] = FCPATH . 'uploads/about/';
                $config['allowed_types'] = 'jpg|jpeg|png|webp';
                $config['max_size'] = 10240;
                $config['encrypt_name'] = TRUE;
                
                if (!is_dir($config['upload_path'])) {
                    mkdir($config['upload_path'], 0755, true);
                }
                
                $this->upload->initialize($config);
                
                if ($this->upload->do_upload('image')) {
                    if ($data['about']->image_path && file_exists(FCPATH . $data['about']->image_path)) {
                        unlink(FCPATH . $data['about']->image_path);
                    }
                    
                    $upload_data = $this->upload->data();
                    $about_data['image_path'] = 'uploads/about/' . $upload_data['file_name'];
                } else {
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect('admin/about/edit/' . $id);
                }
            }
            
            if ($this->input->post('remove_image') && $data['about']->image_path) {
                if (file_exists(FCPATH . $data['about']->image_path)) {
                    unlink(FCPATH . $data['about']->image_path);
                }
                $about_data['image_path'] = null;
            }
            
            if ($this->About_model->update_about($id, $about_data)) {
                $this->session->set_flashdata('success', 'About section updated successfully!');
            } else {
                $this->session->set_flashdata('error', 'Error updating about section. Please try again.');
            }
            
            redirect('admin/about');
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/edit_about', $data);
        $this->load->view('admin/footer');
    }
    
    public function add_about_section() {
        $this->check_login();
        
        if ($this->input->post()) {
            $about_data = array(
                'title' => $this->input->post('title'),
                'content' => $this->input->post('content'),
                'quote' => $this->input->post('quote'),
                'display_order' => $this->input->post('display_order') ?: 0
            );
            
            if (!empty($_FILES['image']['name'])) {
                $config['upload_path'] = FCPATH . 'uploads/about/';
                $config['allowed_types'] = 'jpg|jpeg|png|webp';
                $config['max_size'] = 10240;
                $config['encrypt_name'] = TRUE;
                
                if (!is_dir($config['upload_path'])) {
                    mkdir($config['upload_path'], 0755, true);
                }
                
                $this->upload->initialize($config);
                
                if ($this->upload->do_upload('image')) {
                    $upload_data = $this->upload->data();
                    $about_data['image_path'] = 'uploads/about/' . $upload_data['file_name'];
                } else {
                    $this->session->set_flashdata('error', $this->upload->display_errors());
                    redirect('admin/about/add');
                }
            }
            
            if ($this->About_model->create_about($about_data)) {
                $this->session->set_flashdata('success', 'About section added successfully!');
            } else {
                $this->session->set_flashdata('error', 'Error adding about section. Please try again.');
            }
            
            redirect('admin/about');
        }
        
        $this->load->view('admin/header');
        $this->load->view('admin/add_about');
        $this->load->view('admin/footer');
    }
    
    public function delete_about($id) {
        $this->check_login();
        
        $about = $this->About_model->get_about_by_id($id);
        if ($about && $about->image_path && file_exists(FCPATH . $about->image_path)) {
            unlink(FCPATH . $about->image_path);
        }
        
        if ($this->About_model->delete_about($id)) {
            $this->session->set_flashdata('success', 'About section deleted successfully!');
        } else {
            $this->session->set_flashdata('error', 'Error deleting about section. Please try again.');
        }
        redirect('admin/about');
    }
    public function add_project_enhanced() {
    $this->check_login();
    
    if ($this->input->post()) {
        $project_data = array(
            'title' => $this->input->post('title'),
            'client_name' => $this->input->post('client_name'),
            'model_name' => $this->input->post('model_name'),
            'description' => $this->input->post('description'),
            'project_size' => $this->input->post('project_size'),
            'display_order' => $this->input->post('display_order') ?: 0,
            'aspect_ratio' => $this->input->post('aspect_ratio'),
            'is_featured' => $this->input->post('is_featured') ? 1 : 0,
            'shoot_date' => $this->input->post('shoot_date')
        );
        
        // Handle thumbnail upload
        if (!empty($_FILES['thumbnail']['name'])) {
            $thumbnail_config = $this->get_upload_config('thumbnails');
            $this->upload->initialize($thumbnail_config);
            
            if ($this->upload->do_upload('thumbnail')) {
                $upload_data = $this->upload->data();
                $project_data['thumbnail_path'] = 'uploads/thumbnails/' . $upload_data['file_name'];
                $project_data['thumbnail_type'] = strpos($upload_data['file_type'], 'video') !== false ? 'video' : 'image';
            }
        }
        
        // Create project
        $project_id = $this->Project_model->create_project($project_data);
        
        if ($project_id) {
            // Handle multiple media files
            if (!empty($_FILES['media_files']['name'][0])) {
                $media_config = $this->get_upload_config('projects');
                $this->upload->initialize($media_config);
                
                $files = $_FILES['media_files'];
                $file_count = count($files['name']);
                
                for ($i = 0; $i < $file_count; $i++) {
                    if ($files['name'][$i]) {
                        $_FILES['media_file']['name'] = $files['name'][$i];
                        $_FILES['media_file']['type'] = $files['type'][$i];
                        $_FILES['media_file']['tmp_name'] = $files['tmp_name'][$i];
                        $_FILES['media_file']['error'] = $files['error'][$i];
                        $_FILES['media_file']['size'] = $files['size'][$i];
                        
                        if ($this->upload->do_upload('media_file')) {
                            $media_data = $this->upload->data();
                            
                            $media_type = strpos($media_data['file_type'], 'video') !== false ? 'video' : 'image';
                            
                            $project_media = array(
                                'project_id' => $project_id,
                                'media_type' => $media_type,
                                'media_path' => 'uploads/projects/' . $media_data['file_name'],
                                'display_order' => $i
                            );
                            
                            $this->Project_model->add_project_media($project_media);
                        }
                    }
                }
            }
            
            $this->session->set_flashdata('success', 'Project created successfully!');
        } else {
            $this->session->set_flashdata('error', 'Error creating project. Please try again.');
        }
        
        redirect('admin/projects');
    }
    
    $this->load->view('admin/header');
    $this->load->view('admin/add_project_enhanced');
    $this->load->view('admin/footer');
}

public function edit_project($id) {
    $this->check_login();
    
    $data['project'] = $this->Project_model->get_project($id);
    $data['project_media'] = $this->Project_model->get_project_media($id);
    
    if (!$data['project']) {
        show_404();
    }
    
    if ($this->input->post()) {
        $project_data = array(
            'title' => $this->input->post('title'),
            'client_name' => $this->input->post('client_name'),
            'model_name' => $this->input->post('model_name'),
            'description' => $this->input->post('description'),
            'project_size' => $this->input->post('project_size'),
            'display_order' => $this->input->post('display_order') ?: 0,
            'aspect_ratio' => $this->input->post('aspect_ratio'),
            'is_featured' => $this->input->post('is_featured') ? 1 : 0,
            'shoot_date' => $this->input->post('shoot_date'),
            'updated_at' => date('Y-m-d H:i:s')
        );
        
        // Handle thumbnail upload
        if (!empty($_FILES['thumbnail']['name'])) {
            $thumbnail_config = $this->get_upload_config('thumbnails');
            $this->upload->initialize($thumbnail_config);
            
            if ($this->upload->do_upload('thumbnail')) {
                // Delete old thumbnail if exists
                if ($data['project']->thumbnail_path && file_exists(FCPATH . $data['project']->thumbnail_path)) {
                    unlink(FCPATH . $data['project']->thumbnail_path);
                }
                
                $upload_data = $this->upload->data();
                $project_data['thumbnail_path'] = 'uploads/thumbnails/' . $upload_data['file_name'];
                $project_data['thumbnail_type'] = strpos($upload_data['file_type'], 'video') !== false ? 'video' : 'image';
            }
        } elseif ($this->input->post('remove_thumbnail') == '1') {
            // Handle Thumbnail Removal
            if ($data['project']->thumbnail_path && file_exists(FCPATH . $data['project']->thumbnail_path)) {
                unlink(FCPATH . $data['project']->thumbnail_path);
            }
            $project_data['thumbnail_path'] = NULL;
            $project_data['thumbnail_type'] = NULL;
        }

        // Handle Gallery Media Uploads
        if (!empty($_FILES['gallery_media']['name'][0])) {
            $media_config = $this->get_upload_config('projects');
            $this->upload->initialize($media_config);
            
            $files = $_FILES['gallery_media'];
            $file_count = count($files['name']);
            
            // Get current max display order
            $current_max_order = $this->db->select_max('display_order')->where('project_id', $id)->get('project_media')->row()->display_order;
            
            for ($i = 0; $i < $file_count; $i++) {
                if ($files['name'][$i]) {
                    $_FILES['single_media']['name'] = $files['name'][$i];
                    $_FILES['single_media']['type'] = $files['type'][$i];
                    $_FILES['single_media']['tmp_name'] = $files['tmp_name'][$i];
                    $_FILES['single_media']['error'] = $files['error'][$i];
                    $_FILES['single_media']['size'] = $files['size'][$i];
                    
                    if ($this->upload->do_upload('single_media')) {
                        $media_data = $this->upload->data();
                        $media_type = strpos($media_data['file_type'], 'video') !== false ? 'video' : 'image';
                        
                        $project_media = array(
                            'project_id' => $id,
                            'media_type' => $media_type,
                            'media_path' => 'uploads/projects/' . $media_data['file_name'],
                            'display_order' => ($current_max_order + 1 + $i)
                        );
                        
                        $this->Project_model->add_project_media($project_media);
                    }
                }
            }
        }
        
        if ($this->Project_model->update_project($id, $project_data)) {
            $this->session->set_flashdata('success', 'Project updated successfully!');
        } else {
            $this->session->set_flashdata('error', 'Error updating project. Please try again.');
        }
        
        redirect('admin/projects');
    }
    
    $this->load->view('admin/header');
    $this->load->view('admin/edit_project', $data);
    $this->load->view('admin/footer');
}

private function get_upload_config($type = 'projects') {
    $config = array();
    
    switch ($type) {
        case 'thumbnails':
            $config['upload_path'] = FCPATH . 'uploads/thumbnails/';
            $config['allowed_types'] = 'jpg|jpeg|png|webp|mp4|mov|avi';
            $config['max_size'] = 20480; // 20MB
            break;
        case 'projects':
            $config['upload_path'] = FCPATH . 'uploads/projects/';
            $config['allowed_types'] = 'jpg|jpeg|png|webp|mp4|mov|avi';
            $config['max_size'] = 51200; // 50MB
            break;
        default:
            $config['upload_path'] = FCPATH . 'uploads/';
            $config['allowed_types'] = '*';
            $config['max_size'] = 51200;
    }
    
    $config['encrypt_name'] = TRUE;
    $config['overwrite'] = FALSE;
    
    // Create directory if it doesn't exist
    if (!is_dir($config['upload_path'])) {
        mkdir($config['upload_path'], 0755, true);
    }
    
    return $config;
}
    // Add to Admin.php controller
public function contact_settings() {
    $this->check_login();
    
    $data['contact_settings'] = $this->Contact_model->get_contact_settings();
    
    if ($this->input->post()) {
        $contact_data = array(
            'hero_title' => $this->input->post('hero_title'),
            'hero_description' => $this->input->post('hero_description'),
            'address' => $this->input->post('address'),
            'phone' => $this->input->post('phone'),
            'email' => $this->input->post('email'),
            'google_map_url' => $this->input->post('google_map_url'),
            'updated_at' => date('Y-m-d H:i:s')
        );
        
        // Handle image upload
        if (!empty($_FILES['contact_image']['name'])) {
            $config['upload_path'] = FCPATH . 'uploads/contact/';
            $config['allowed_types'] = 'jpg|jpeg|png|webp';
            $config['max_size'] = 10240;
            $config['encrypt_name'] = TRUE;
            
            if (!is_dir($config['upload_path'])) {
                mkdir($config['upload_path'], 0755, true);
            }
            
            $this->upload->initialize($config);
            
            if ($this->upload->do_upload('contact_image')) {
                // Delete old image if exists
                if ($data['contact_settings']->contact_image && file_exists(FCPATH . $data['contact_settings']->contact_image)) {
                    unlink(FCPATH . $data['contact_settings']->contact_image);
                }
                
                $upload_data = $this->upload->data();
                $contact_data['contact_image'] = 'uploads/contact/' . $upload_data['file_name'];
            } else {
                $this->session->set_flashdata('error', $this->upload->display_errors());
                redirect('admin/contact-settings');
            }
        }
        
        // Handle image removal
        if ($this->input->post('remove_image') && $data['contact_settings']->contact_image) {
            if (file_exists(FCPATH . $data['contact_settings']->contact_image)) {
                unlink(FCPATH . $data['contact_settings']->contact_image);
            }
            $contact_data['contact_image'] = null;
        }
        
        if ($this->Contact_model->update_contact_settings($contact_data)) {
            $this->session->set_flashdata('success', 'Contact settings updated successfully!');
        } else {
            $this->session->set_flashdata('error', 'Error updating contact settings. Please try again.');
        }
        
        redirect('admin/contact-settings');
    }
    
    $this->load->view('admin/header');
    $this->load->view('admin/contact_settings', $data);
    $this->load->view('admin/footer');
}
    
    public function homepage_editor() {
        $this->check_login();
        
        // Auto-create table if not exists (Temporary fix for CLI issues)
        $this->db->query("CREATE TABLE IF NOT EXISTS homepage_layout (
            id INT AUTO_INCREMENT PRIMARY KEY,
            project_id INT NOT NULL,
            x_pos DECIMAL(10,2) DEFAULT 0,
            y_pos DECIMAL(10,2) DEFAULT 0,
            width DECIMAL(10,2) DEFAULT 20,
            height DECIMAL(10,2) DEFAULT 0,
            z_index INT DEFAULT 1,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )");
        
        // Ensure columns are large enough (Fix for truncation issue on items > 999px)
        $this->db->query("ALTER TABLE homepage_layout MODIFY x_pos DECIMAL(12,2) DEFAULT 0");
        $this->db->query("ALTER TABLE homepage_layout MODIFY y_pos DECIMAL(12,2) DEFAULT 0");
        $this->db->query("ALTER TABLE homepage_layout MODIFY width DECIMAL(12,2) DEFAULT 0");
        $this->db->query("ALTER TABLE homepage_layout MODIFY height DECIMAL(12,2) DEFAULT 0");
        
        // Fetch all projects for the sidebar
        $data['projects'] = $this->Project_model->get_all_projects();
        
        // Fetch current layout
        $data['layout'] = $this->db->get('homepage_layout')->result_array();

        // Fetch Canvas Height Setting
        $data['canvas_height'] = $this->Project_model->get_setting('homepage_canvas_height');
        
        $this->load->view('admin/homepage_editor', $data);
    }

    public function update_homepage_layout() {
        if (!$this->session->userdata('admin_logged_in')) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($input['items'])) {
            echo json_encode(['success' => false, 'message' => 'No data provided']);
            return;
        }

        // Save Canvas Height if provided
        if(isset($input['canvas_height'])) {
            $this->Project_model->save_setting('homepage_canvas_height', $input['canvas_height']);
        }

        // Empty the current layout table
        $this->db->truncate('homepage_layout');
        
        // Insert new items
        $data = [];
        foreach ($input['items'] as $item) {
            $data[] = [
                'project_id' => $item['project_id'],
                'x_pos' => $item['x'],
                'y_pos' => $item['y'],
                'width' => $item['width'],
                'height' => $item['height'],
                'z_index' => isset($item['z_index']) ? $item['z_index'] : 1
            ];
        }
        
        $this->db->insert_batch('homepage_layout', $data);
        
        echo json_encode(['success' => true]);
    }

    public function delete_media($id) {
         $this->check_login();
         $media = $this->db->where('id', $id)->get('project_media')->row();
         if ($media) {
             $this->Project_model->delete_project_media($id);
             $this->session->set_flashdata('success', 'Media deleted.');
             redirect('admin/projects/edit/' . $media->project_id);
         } else {
             $this->session->set_flashdata('error', 'Media not found.');
             redirect('admin/projects');
         }
    }

    public function delete_inquiry($id) {
        $this->check_login();
        $this->db->where('id', $id);
        $this->db->delete('contact_inquiries');
        $this->session->set_flashdata('success', 'Inquiry deleted.');
        redirect('admin/contact_inquiries');
    }

}
?>
