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

class Comments extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('Comment_model');
        $this->load->helper('url');
        
        // Enable CORS
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');
        header('Content-Type: application/json');
        
        // Handle preflight requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit(0);
        }
    }

    private function json_response($data, $status_code = 200) {
        $this->output
            ->set_status_header($status_code)
            ->set_content_type('application/json')
            ->set_output(json_encode($data));
    }

    public function index() {
        try {
            $limit = $this->input->get('limit');
            
            if ($limit === 'all') {
                // Fetch all approved comments for build processes
                $comments = $this->Comment_model->get_all_comments();
                $total = count($comments);
                
                $this->json_response([
                    'data' => $comments,
                    'total' => $total,
                    'page' => 1,
                    'limit' => -1
                ]);
            } else {
                // Standard paginated response (if needed in future)
                $page = $this->input->get('page') ? (int)$this->input->get('page') : 1;
                $limit = $limit ? (int)$limit : 10;
                $offset = ($page - 1) * $limit;
                
                $comments = $this->Comment_model->get_all_comments($limit, $offset);
                $total = $this->Comment_model->count_all_comments();
                
                $this->json_response([
                    'data' => $comments,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]);
            }
        } catch (Exception $e) {
            $this->json_response(['error' => $e->getMessage()], 500);
        }
    }

    public function get_comments() {
        try {
            $type = $this->input->get('type');
            $item_id = $this->input->get('item_id');

            if (!$type || !$item_id) {
                $this->json_response(['error' => 'Type and item_id are required'], 400);
                return;
            }

            $comments = $this->Comment_model->get_comments($type, $item_id);
            $this->json_response($comments);
        } catch (Exception $e) {
            $this->json_response(['error' => $e->getMessage()], 500);
        }
    }

    public function add_comment() {
        try {
            // Handle both JSON and form-encoded data
            $json_data = null;
            $content_type = $_SERVER['CONTENT_TYPE'] ?? '';
            
            if (strpos($content_type, 'application/json') !== false) {
                $json_input = file_get_contents('php://input');
                $json_data = json_decode($json_input, true);
                error_log('JSON data received: ' . print_r($json_data, true));
            }
            
            // Debug: Log all POST data and FILES
            error_log('POST data: ' . print_r($_POST, true));
            error_log('FILES data: ' . print_r($_FILES, true));
            
            // Get data from JSON or POST
            $name = $json_data['name'] ?? $this->input->post('name');
            $message = $json_data['message'] ?? $this->input->post('message');
            $type = $json_data['type'] ?? $this->input->post('type');
            $item_id = $json_data['item_id'] ?? $this->input->post('item_id');

            if (!$name || !$message || !$type || !$item_id) {
                $this->json_response(['error' => 'Name, message, type, and item_id are required'], 400);
                return;
            }
            // Get rating for product comments
            $rating = null;
            if ($type === 'product') {
                $rating_raw = $json_data['rating'] ?? $this->input->post('rating');
                error_log('Raw rating from JSON/POST: ' . var_export($rating_raw, true));
                
                if ($rating_raw !== null && $rating_raw !== '' && $rating_raw !== false) {
                    $rating = intval($rating_raw);
                    error_log('Converted rating: ' . $rating);
                    if ($rating < 1 || $rating > 5) {
                        $this->json_response(['error' => 'Rating must be between 1 and 5'], 400);
                        return;
                    }
                } else {
                    error_log('Rating is null, empty, or false');
                    $rating = null;
                }
            }

            $data = array(
                'name' => $name,
                'email' => $this->input->post('email'),
                'message' => $message,
                'type' => $type,
                'item_id' => $item_id,
                'rating' => $rating
            );

            // Handle profile picture upload (single image)
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $profile_config = array(
                    'upload_path' => './uploads/comments/',
                    'allowed_types' => 'jpg|jpeg|png|gif|webp',
                    'max_size' => 2048, // 2MB
                    'encrypt_name' => TRUE,
                    'remove_spaces' => TRUE
                );

                $this->load->library('upload', $profile_config);

                if ($this->upload->do_upload('image')) {
                    $upload_data = $this->upload->data();
                    $data['image'] = $upload_data['file_name'];
                } else {
                    $data['image'] = null;
                }
            } else {
                $data['image'] = null;
            }

            // Handle multiple images upload (lampiran - max 5 images)
            $uploaded_images = array();
            // PHP converts 'images[]' to 'images' automatically in $_FILES
            if (isset($_FILES['images']) && is_array($_FILES['images']['name']) && !empty($_FILES['images']['name'][0])) {
                // Create images directory if it doesn't exist
                if (!is_dir('./uploads/comments/images/')) {
                    mkdir('./uploads/comments/images/', 0755, true);
                }

                $images_config = array(
                    'upload_path' => './uploads/comments/images/',
                    'allowed_types' => 'jpg|jpeg|png|gif|webp',
                    'max_size' => 2048, // 2MB per image
                    'encrypt_name' => TRUE,
                    'remove_spaces' => TRUE
                );

                // Load a new upload instance for multiple images
                $this->load->library('upload');
                $this->upload->initialize($images_config);

                // Process each uploaded image (max 5)
                $file_count = min(count($_FILES['images']['name']), 5);
                for ($i = 0; $i < $file_count; $i++) {
                    if ($_FILES['images']['error'][$i] == 0) {
                        $_FILES['single_image']['name'] = $_FILES['images']['name'][$i];
                        $_FILES['single_image']['type'] = $_FILES['images']['type'][$i];
                        $_FILES['single_image']['tmp_name'] = $_FILES['images']['tmp_name'][$i];
                        $_FILES['single_image']['error'] = $_FILES['images']['error'][$i];
                        $_FILES['single_image']['size'] = $_FILES['images']['size'][$i];

                        if ($this->upload->do_upload('single_image')) {
                            $upload_data = $this->upload->data();
                            $uploaded_images[] = $upload_data['file_name'];
                        }
                        // Reset for next file
                        $this->upload->initialize($images_config);
                    }
                }
            }
            
            // Store images as JSON array and add to data array
            $data['images'] = !empty($uploaded_images) ? json_encode($uploaded_images) : null;
            
            // Debug: Log what we're about to save
            error_log('Data to save: ' . print_r($data, true));
            error_log('Uploaded images: ' . print_r($uploaded_images, true));

            // Handle attachment upload (only for products)
            if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
                // Create attachments directory if it doesn't exist
                if (!is_dir('./uploads/comments/attachments/')) {
                    mkdir('./uploads/comments/attachments/', 0755, true);
                }

                // Create a new upload instance for attachment
                $attachment_config = array(
                    'upload_path' => './uploads/comments/attachments/',
                    'allowed_types' => 'jpg|jpeg|png|gif|webp|pdf|doc|docx|txt',
                    'max_size' => 5120, // 5MB
                    'encrypt_name' => TRUE, // Randomize filename
                    'remove_spaces' => TRUE,
                    'overwrite' => FALSE
                );

                // Clear any previous upload errors and reinitialize
                $this->upload->initialize($attachment_config);

                if ($this->upload->do_upload('attachment')) {
                    $upload_data = $this->upload->data();
                    $data['attachment'] = $upload_data['file_name'];
                } else {
                    // Handle upload error
                    $data['attachment'] = null;
                }
            } else {
                $data['attachment'] = null;
            }

            // Debug: Final data before saving
            error_log('Final data before model save: ' . print_r($data, true));
            
            $result = $this->Comment_model->add_comment($data);
            
            // Debug: Save result
            error_log('Save result: ' . var_export($result, true));

            if ($result) {
                $this->json_response(['message' => 'Comment submitted successfully and pending approval']);
            } else {
                $this->json_response(['error' => 'Failed to submit comment'], 500);
            }
        } catch (Exception $e) {
            $this->json_response(['error' => $e->getMessage()], 500);
        }
    }

    // Admin endpoints for managing comments
    public function get_pending_comments() {
        try {
            // Add authentication check here
            $comments = $this->Comment_model->get_pending_comments();
            $this->json_response($comments);
        } catch (Exception $e) {
            $this->json_response(['error' => $e->getMessage()], 500);
        }
    }

    public function approve_comment($comment_id) {
        try {
            // Add authentication check here
            $result = $this->Comment_model->approve_comment($comment_id);
            $this->json_response(['success' => $result]);
        } catch (Exception $e) {
            $this->json_response(['error' => $e->getMessage()], 500);
        }
    }

    public function reject_comment($comment_id) {
        try {
            // Add authentication check here
            $result = $this->Comment_model->reject_comment($comment_id);
            $this->json_response(['success' => $result]);
        } catch (Exception $e) {
            $this->json_response(['error' => $e->getMessage()], 500);
        }
    }
} 