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

class Holiday extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper(['url', 'form']);
        $this->load->library('session');
        $this->load->model('Holiday_model');
        
        // Check authentication
        $login_id = $this->session->userdata('id');
        if (empty($login_id)) {
            if ($this->input->is_ajax_request()) {
                echo json_encode(['success' => false, 'message' => 'Session expired']);
                exit;
            }
            redirect('login');
        }
    }

    /**
     * Main holiday list page
     */
    public function index()
    {
        $this->session->set_userdata('menu', 'holiday');
        
        // Ensure country column exists
        $this->Holiday_model->ensureCountryColumn();
        
        $year = $this->input->get('year') ?: date('Y');
        $company_id = $this->input->get('company_id') ?: $this->session->userdata('company_id');
        
        // Get company's country
        $country = null;
        $selected_company = null;
        if (!empty($company_id)) {
            $selected_company = $this->db->get_where('company', ['id' => $company_id])->row();
            if ($selected_company) {
                $country = $selected_company->country;
            }
        }
        
        // Get list of companies for dropdown
        $role_id = $this->session->userdata('role_id');
        $login_id = $this->session->userdata('id');
        
        if (is_super_admin()) {
            // Super Admin - see all companies
            $companies = $this->db->select('id, company_name, country')
                ->where('status', '1')
                ->order_by('company_name', 'ASC')
                ->get('company')
                ->result();
        } else {
            // Admin and User - see only assigned companies
            $allowed_companies = get_allowed_companies();
            if (!empty($allowed_companies)) {
                $companies = $this->db->select('id, company_name, country')
                    ->where('status', '1')
                    ->where_in('id', $allowed_companies)
                    ->order_by('company_name', 'ASC')
                    ->get('company')
                    ->result();
            } else {
                $companies = [];
            }
        }
        
        // Years from 2024 (system start) to current year + 1 (for advance planning)
        $startYear = 2024;
        $endYear = date('Y') + 1;
        $years = [];
        for ($y = $endYear; $y >= $startYear; $y--) {
            $years[] = $y;
        }
        
        $data = [
            'holidays' => $this->Holiday_model->getHolidaysByYear($year, $country),
            'selected_year' => $year,
            'selected_company_id' => $company_id,
            'selected_company' => $selected_company,
            'selected_country' => $country,
            'companies' => $companies,
            'years' => $years
        ];
        
        $this->load->view('templates/header', $data);
        $this->load->view('holiday/index', $data);
        $this->load->view('templates/footer');
    }

    /**
     * Add a single holiday via AJAX
     */
    public function add()
    {
        // Permission check - edit permission required
        if (!can_edit()) {
            echo json_encode(['success' => false, 'message' => 'You do not have permission to add holidays.']);
            return;
        }
        
        $date = $this->input->post('date');
        $name = $this->input->post('name');
        $company_id = $this->input->post('company_id');
        
        if (empty($date) || empty($name)) {
            echo json_encode(['success' => false, 'message' => 'Date and name are required.']);
            return;
        }
        
        // Get country from company
        $country = 'India'; // Default
        if (!empty($company_id)) {
            $company = $this->db->get_where('company', ['id' => $company_id])->row();
            if ($company && !empty($company->country)) {
                $country = $company->country;
            }
        }
        
        // Check for duplicate holiday on the same date
        $existing = $this->db->where('holiday_date', $date)->where('country', $country)->get('holidays')->row();
        if ($existing) {
            echo json_encode(['success' => false, 'message' => 'A holiday already exists on this date for ' . $country . '.']);
            return;
        }
        
        $result = $this->Holiday_model->addHoliday($date, $name, $country);
        echo json_encode($result);
    }

    /**
     * Delete a holiday via AJAX
     */
    public function delete()
    {
        // Permission check - delete permission required
        if (!can_delete()) {
            echo json_encode(['success' => false, 'message' => 'You do not have permission to delete holidays.']);
            return;
        }
        
        $id = $this->input->post('id');
        
        if (empty($id)) {
            echo json_encode(['success' => false, 'message' => 'Invalid holiday ID.']);
            return;
        }
        
        $result = $this->Holiday_model->deleteHoliday($id);
        echo json_encode($result);
    }

    /**
     * Import holidays from CSV file
     */
    public function import()
    {
        // Permission check - edit permission required
        if (!can_edit()) {
            echo json_encode(['success' => false, 'message' => 'You do not have permission to import holidays.']);
            return;
        }
        
        $year = $this->input->post('year') ?: date('Y');
        $company_id = $this->input->post('company_id');
        
        // Get country from company
        $country = 'India'; // Default
        if (!empty($company_id)) {
            $company = $this->db->get_where('company', ['id' => $company_id])->row();
            if ($company && !empty($company->country)) {
                $country = $company->country;
            }
        }
        
        // Check if file was uploaded
        if (empty($_FILES['file']['name'])) {
            echo json_encode(['success' => false, 'message' => 'No file uploaded. Please select a file.']);
            return;
        }
        
        // Use hardcoded path like other controllers in this project
        //$config['upload_path']   = 'c:/xampp/htdocs/dms/uploads/temp/';
        $config['upload_path'] = $this->config->item('documents_upload_path');
        $config['allowed_types'] = 'csv|xlsx|xls';
        $config['max_size']      = 2048;
        $config['file_name']     = 'holidays_' . time();
        $config['overwrite']     = TRUE;
        
        // Create directory if it doesn't exist
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }
        
        // Load library then initialize - same pattern as upload.php controller
        $this->load->library('upload');
        $this->upload->initialize($config);
        
        if (!$this->upload->do_upload('file')) {
            echo json_encode(['success' => false, 'message' => $this->upload->display_errors('', '')]);
            return;
        }
        
        $uploadData = $this->upload->data();
        $filePath = $uploadData['full_path'];
        $ext = strtolower($uploadData['file_ext']);
        
        $holidays = [];
        
        if ($ext == '.csv') {
            // Parse CSV
            if (($handle = fopen($filePath, "r")) !== FALSE) {
                $header = fgetcsv($handle); // Skip header row
                
                while (($row = fgetcsv($handle)) !== FALSE) {
                    if (count($row) >= 2) {
                        $dateVal = trim($row[0]);
                        $nameVal = trim($row[1]);
                        
                        // Parse date - handle multiple formats
                        $parsedDate = $this->_parseDate($dateVal);
                        if ($parsedDate !== false) {
                            $holidays[] = [
                                'date' => $parsedDate,
                                'name' => $nameVal
                            ];
                        }
                    }
                }
                fclose($handle);
            }
        } else {
            // For Excel files, use PhpSpreadsheet
            try {
                require_once FCPATH . 'vendor/autoload.php';
                
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
                $sheet = $spreadsheet->getActiveSheet();
                $rows = $sheet->toArray();
                
                // Skip header row
                for ($i = 1; $i < count($rows); $i++) {
                    $row = $rows[$i];
                    if (count($row) >= 2 && !empty($row[0])) {
                        $dateVal = trim($row[0]);
                        $nameVal = trim($row[1]);
                        
                        // Try to parse date
                        if (is_numeric($dateVal)) {
                            // Excel date serial number
                            $timestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($dateVal);
                            $parsedDate = date('Y-m-d', $timestamp);
                        } else {
                            $parsedDate = $this->_parseDate($dateVal);
                        }
                        
                        if ($parsedDate !== false) {
                            $holidays[] = [
                                'date' => $parsedDate,
                                'name' => $nameVal
                            ];
                        }
                    }
                }
            } catch (Exception $e) {
                @unlink($filePath);
                echo json_encode(['success' => false, 'message' => 'Error reading Excel file: ' . $e->getMessage()]);
                return;
            }
        }
        
        // Clean up uploaded file
        @unlink($filePath);
        
        if (empty($holidays)) {
            echo json_encode(['success' => false, 'message' => 'No valid holidays found in file.']);
            return;
        }
        
        $result = $this->Holiday_model->importHolidays($holidays, $year, $country);
        echo json_encode([
            'success' => true,
            'message' => "Import complete for {$country}. Added: {$result['added']}, Skipped (duplicates): {$result['skipped']}"
        ]);
    }

    /**
     * Clear all holidays for a year
     */
    public function clearYear()
    {
        // Permission check - delete permission required
        if (!can_delete()) {
            echo json_encode(['success' => false, 'message' => 'You do not have permission to clear holidays.']);
            return;
        }
        
        $year = $this->input->post('year');
        
        if (empty($year)) {
            echo json_encode(['success' => false, 'message' => 'Year is required.']);
            return;
        }
        
        $result = $this->Holiday_model->clearHolidaysForYear($year);
        echo json_encode(['success' => true, 'message' => "All holidays for $year have been cleared."]);
    }

    /**
     * Get holidays for a year via AJAX
     */
    public function getHolidays()
    {
        $year = $this->input->post('year') ?: date('Y');
        $holidays = $this->Holiday_model->getHolidaysByYear($year);
        echo json_encode(['success' => true, 'holidays' => $holidays]);
    }

    /**
     * API: Get adjusted due date
     */
    public function getAdjustedDueDate()
    {
        $dueDay = (int)$this->input->post('due_day');
        $month = (int)$this->input->post('month');
        $year = (int)$this->input->post('year');
        
        if (!$dueDay || !$month || !$year) {
            echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
            return;
        }
        
        $result = $this->Holiday_model->getAdjustedDueDate($dueDay, $month, $year);
        echo json_encode(['success' => true, 'data' => $result]);
    }

    /**
     * Download sample CSV template
     */
    public function downloadTemplate()
    {
        $data = "Date,Holiday Name\n";
        $data .= "01-01-2025,New Year's Day\n";
        $data .= "26-01-2025,Republic Day\n";
        $data .= "15-08-2025,Independence Day\n";
        $data .= "02-10-2025,Gandhi Jayanti\n";
        $data .= "25-12-2025,Christmas\n";
        
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="holiday_template.csv"');
        echo $data;
        exit;
    }

    /**
     * Parse date string to Y-m-d format
     * Handles DD-MM-YYYY, DD/MM/YYYY, YYYY-MM-DD formats
     */
    private function _parseDate($dateStr)
    {
        if (empty($dateStr)) {
            return false;
        }
        
        $dateStr = trim($dateStr);
        
        // Try DD-MM-YYYY format first (most common in India)
        $date = DateTime::createFromFormat('d-m-Y', $dateStr);
        if ($date !== false) {
            return $date->format('Y-m-d');
        }
        
        // Try DD/MM/YYYY format
        $date = DateTime::createFromFormat('d/m/Y', $dateStr);
        if ($date !== false) {
            return $date->format('Y-m-d');
        }
        
        // Try YYYY-MM-DD format (ISO)
        $date = DateTime::createFromFormat('Y-m-d', $dateStr);
        if ($date !== false) {
            return $date->format('Y-m-d');
        }
        
        // Try YYYY/MM/DD format
        $date = DateTime::createFromFormat('Y/m/d', $dateStr);
        if ($date !== false) {
            return $date->format('Y-m-d');
        }
        
        // Try MM-DD-YYYY format (US)
        $date = DateTime::createFromFormat('m-d-Y', $dateStr);
        if ($date !== false) {
            return $date->format('Y-m-d');
        }
        
        // Try MM/DD/YYYY format (US)
        $date = DateTime::createFromFormat('m/d/Y', $dateStr);
        if ($date !== false) {
            return $date->format('Y-m-d');
        }
        
        // Fallback to strtotime (for other formats like "January 1, 2025")
        $timestamp = strtotime($dateStr);
        if ($timestamp !== false) {
            return date('Y-m-d', $timestamp);
        }
        
        return false;
    }
}

