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

// Require your custom database connection
require_once FCPATH . '../dripend/includes/db.php';

class Facility_profile extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    public function save() {
        // Force output to be standard JSON
        header('Content-Type: application/json');

        // We use \Throwable here to catch FATAL PHP ERRORS that normally crash the server silently
        try {
            
            // --- DATABASE CONNECTION CHECK ---
            // If your db.php uses a variable like $conn or $pdo instead of the Database class,
            // we will catch the error gracefully and tell you in the modal!
            if (class_exists('Database')) {
                $db = Database::getInstance()->getConnection();
            } else {
                // Adjust this line if your db.php uses a different variable name (e.g., $conn, $mysqli)
                global $pdo; 
                $db = $pdo; 
                if (!$db) {
                    throw new Exception("Database connection variable not found. Please check your db.php file.");
                }
            }

            // 1. Capture Form Data
            $hospital_name = $this->input->post('hospital_name', TRUE) ?: 'RiMax Health Suite';
            $tax_id        = $this->input->post('tax_id', TRUE) ?: '';
            $primary_phone = $this->input->post('primary_phone', TRUE) ?: '';
            $sec_phone     = $this->input->post('secondary_phone', TRUE) ?: '';
            $primary_email = $this->input->post('primary_email', TRUE) ?: '';
            $sec_email     = $this->input->post('secondary_email', TRUE) ?: '';
            $address       = $this->input->post('address', TRUE) ?: '';
            $doc_align     = $this->input->post('header_alignment', TRUE) ?: 'center';
            $primary_hex   = $this->input->post('primary_hex', TRUE) ?: '#1E3A8A';
            $accent_hex    = $this->input->post('accent_hex', TRUE) ?: '#3B82F6';
            $id_format     = $this->input->post('id_format', TRUE) ?: 'FMT_B';
            $id_padding    = $this->input->post('id_padding', TRUE) ?: 5;
            $opd_prefix    = strtoupper($this->input->post('opd_prefix', TRUE) ?: 'RMX');

            $enable_dual   = $this->input->post('dual_logo_toggle') ? 1 : 0;
            $print_photo   = $this->input->post('print_photo') ? 1 : 0;
            $print_blood   = $this->input->post('print_blood') ? 1 : 0;

            // 2. Handle File Uploads
            $upload_dir = FCPATH . 'application/views/system_setup/setupUploads/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

            $primary_logo_path = null;
            if (isset($_FILES['primary_logo']) && $_FILES['primary_logo']['error'] === UPLOAD_ERR_OK) {
                $ext = pathinfo($_FILES['primary_logo']['name'], PATHINFO_EXTENSION);
                $filename = 'primary_logo_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['primary_logo']['tmp_name'], $upload_dir . $filename)) {
                    $primary_logo_path = 'setupUploads/' . $filename; 
                }
            }

            $secondary_logo_path = null;
            if ($enable_dual && isset($_FILES['secondary_logo']) && $_FILES['secondary_logo']['error'] === UPLOAD_ERR_OK) {
                $ext = pathinfo($_FILES['secondary_logo']['name'], PATHINFO_EXTENSION);
                $filename = 'secondary_logo_' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['secondary_logo']['tmp_name'], $upload_dir . $filename)) {
                    $secondary_logo_path = 'setupUploads/' . $filename;
                }
            }

            // 3. Database Upsert Logic
            $sql = "INSERT INTO facility_profile 
                    (id, hospital_name, tax_id, primary_phone, secondary_phone, primary_email, secondary_email, address, enable_dual_logo, document_alignment, primary_hex, accent_hex, id_format, id_padding, opd_prefix, print_photo, print_blood_group) 
                    VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 
                    ON DUPLICATE KEY UPDATE 
                    hospital_name=VALUES(hospital_name), tax_id=VALUES(tax_id), primary_phone=VALUES(primary_phone), secondary_phone=VALUES(secondary_phone), primary_email=VALUES(primary_email), secondary_email=VALUES(secondary_email), address=VALUES(address), enable_dual_logo=VALUES(enable_dual_logo), document_alignment=VALUES(document_alignment), primary_hex=VALUES(primary_hex), accent_hex=VALUES(accent_hex), id_format=VALUES(id_format), id_padding=VALUES(id_padding), opd_prefix=VALUES(opd_prefix), print_photo=VALUES(print_photo), print_blood_group=VALUES(print_blood_group)";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([$hospital_name, $tax_id, $primary_phone, $sec_phone, $primary_email, $sec_email, $address, $enable_dual, $doc_align, $primary_hex, $accent_hex, $id_format, $id_padding, $opd_prefix, $print_photo, $print_blood]);

            if ($primary_logo_path) {
                $db->prepare("UPDATE facility_profile SET primary_logo_path = ? WHERE id = 1")->execute([$primary_logo_path]);
            }
            if ($secondary_logo_path) {
                $db->prepare("UPDATE facility_profile SET secondary_logo_path = ? WHERE id = 1")->execute([$secondary_logo_path]);
            }

            echo json_encode(['status' => 'success', 'message' => 'Configuration saved successfully!']);

        } catch (\Throwable $e) {
            // Catches ALL errors, including Fatal PHP crashes
            http_response_code(500);
            echo json_encode(['status' => 'error', 'message' => 'System Error: ' . $e->getMessage()]);
        }
    }
}