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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class Save_health_checkup extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Book_A_Health_Checkup_Model');
        $this->load->model('Email_Format_Model', 'email_format_model');
        $this->load->model('Admin_Email_Format_Model', 'admin_email_format_model');
        $this->load->model('Email_Notification_Settings_Model', 'ens_model');

        require_once APPPATH.'third_party/PHPMailer/Exception.php';
        require_once APPPATH.'third_party/PHPMailer/PHPMailer.php';
        require_once APPPATH.'third_party/PHPMailer/SMTP.php';
    }

    private function sendMail($from, $to, $subject, $body)
    {
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'localhost';
            $mail->SMTPAuth   = false;
            $mail->Port       = 25;
            $mail->CharSet    = 'UTF-8';

            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            $mail->setFrom($from, 'Synergy Hospital');
            $recipients = explode(',', $to);
            foreach ($recipients as $recipient) {
                $mail->addAddress(trim($recipient));
            }
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            $mail->send();
            return true;
        } catch (Exception $e) {
            log_message('error', 'PHPMailer Error: ' . $mail->ErrorInfo);
            file_put_contents(FCPATH . 'phpmailer_debug.txt', date('Y-m-d H:i:s') . " - Error: " . $mail->ErrorInfo . "\n", FILE_APPEND);
            return false;
        }
    }

    private function replacePlaceholders($template, $data)
    {
        foreach ($data as $key => $value) {
            $template = str_replace('{' . $key . '}', htmlspecialchars($value ?? ''), $template);
        }
        return $template;
    }

    private function buildEmailBody($top_desc, $bottom_desc, $table_rows_html)
    {
        return '
         <div style="font-family:Arial,sans-serif;max-width:600px;margin:auto;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden;">
          <div style="background:#003773;padding:20px;text-align:center;">
            <h2 style="color:#fff;margin:0;">Synergy Hospital</h2>
          </div>
          <div style="padding:30px;">
            <div style="margin-bottom:15px;">' . $top_desc . '</div>
            <table style="width:100%;border-collapse:collapse;margin:15px 0;">' . $table_rows_html . '</table>
            <div style="margin-top:15px;color:#555;">' . $bottom_desc . '</div>
          </div>
          <div style="background:#f5f5f5;padding:15px;text-align:center;font-size:12px;color:#999;">
            Synergy Hospital &mdash; enquiry@synergyhospital.co.in
          </div>
        </div>';
    }

    public function index()
    {
        header("Access-Control-Allow-Origin: https://synergyhospital.co.in/");
        header("Access-Control-Allow-Methods: POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type");
        header("Content-Type: application/json");

        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

        if ($this->input->method(TRUE) !== 'POST') {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
            return;
        }

        $input = json_decode(file_get_contents("php://input"), true);
        if (!$input) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
            return;
        }

        $data = [
            'patient_name'    => $input['patient_name'],
            'patient_mobile'  => $input['patient_mobile'],
            'patient_email'   => $input['patient_email'],
            'appontment_date' => $input['appontment_date'],
            'appontment_time' => $input['appontment_time'],
            'package_name'    => $input['package_name'],
            'decription'      => $input['decription'] ?? null,
            'status'          => '1',
            'publish'         => '1',
            'date_time'       => date('Y-m-d H:i:s')
        ];

        $insert_id = $this->Book_A_Health_Checkup_Model->save($data);

        if ($insert_id) {

            $placeholders = [
                'patient_name'   => $data['patient_name'],
                'patient_mobile' => $data['patient_mobile'],
                'patient_email'  => $data['patient_email'],
                'package_name'   => $data['package_name'],
                'date'           => $data['appontment_date'],
                'time'           => $data['appontment_time'],
                'description'    => $data['decription'] ?? '-',
                'hospital_name'  => 'Synergy Hospital',
                'hospital_phone' => '+91 95121 40075',
                'hospital_email' => 'enquiry@synergyhospital.co.in',
            ];

            $table_rows = '
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Package</strong></td><td style="padding:10px;border:1px solid #dde;">{package_name}</td></tr>
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Date</strong></td><td style="padding:10px;border:1px solid #dde;">{date}</td></tr>
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Time</strong></td><td style="padding:10px;border:1px solid #dde;">{time}</td></tr>
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Mobile</strong></td><td style="padding:10px;border:1px solid #dde;">{patient_mobile}</td></tr>
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Description</strong></td><td style="padding:10px;border:1px solid #dde;">{description}</td></tr>';
            $table_rows = $this->replacePlaceholders($table_rows, $placeholders);

            // Fetch Email settings from database
            $from_email = 'system@synergyhospital.co.in';
            $to_email = 'frontoffice@synergyhospital.co.in';
            $settings = $this->ens_model->get_by_form_key('health_checkup');
            if ($settings) {
                if (!empty($settings->from_email)) $from_email = $settings->from_email;
                if (!empty($settings->to_emails)) $to_email = $settings->to_emails;
            }

            // ========== Patient Email (Template ID = 2 for Health Checkup) ==========
            $patient_tpl = $this->email_format_model->get_by_id(2);
            if ($patient_tpl) {
                $p_subject = $this->replacePlaceholders($patient_tpl->subject, $placeholders);
                $p_top     = $this->replacePlaceholders($patient_tpl->top_description, $placeholders);
                $p_bottom  = $this->replacePlaceholders($patient_tpl->bottom_description, $placeholders);
                $p_body    = $this->buildEmailBody($p_top, $p_bottom, $table_rows);
            } else {
                $p_subject = "Health Checkup Booking Confirmation - Synergy Hospital";
                $p_body    = $this->buildEmailBody(
                    'Dear <strong>' . htmlspecialchars($data['patient_name']) . '</strong>, your health checkup has been booked successfully.',
                    'Please arrive 15 minutes before your scheduled time. Call: <strong>+91 95121 40075</strong>.',
                    $table_rows
                );
            }
            if (!empty($data['patient_email'])) {
                $this->sendMail($from_email, $data['patient_email'], $p_subject, $p_body);
            }

            // ========== Admin Email (Template ID = 2 for Health Checkup) ==========
            $admin_tpl = $this->admin_email_format_model->get_by_id(2);
            if ($admin_tpl) {
                $a_subject = $this->replacePlaceholders($admin_tpl->subject, $placeholders);
                $a_top     = $this->replacePlaceholders($admin_tpl->top_description, $placeholders);
                $a_bottom  = $this->replacePlaceholders($admin_tpl->bottom_description, $placeholders);
                $a_body    = $this->buildEmailBody($a_top, $a_bottom, $table_rows);
            } else {
                $a_subject = "New Health Checkup Booking - " . $data['patient_name'];
                $a_body    = $this->buildEmailBody(
                    'New health checkup booking from <strong>' . htmlspecialchars($data['patient_name']) . '</strong>.',
                    'Log in to admin panel for details.',
                    $table_rows
                );
            }
            $this->sendMail($from_email, $to_email, $a_subject, $a_body);

            echo json_encode(['status' => 'success', 'message' => 'Health checkup booked successfully', 'id' => $insert_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
    }
}
