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

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

class Save_Appointment extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Book_An_Appointment_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);
            return false;
        }
    }

    /**
     * Template ke placeholders ko actual data se replace karo
     * Admin Panel mein {patient_name}, {doctor_name} etc. use karo
     */
    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, Authorization");
    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;
    }

    $dateObj = DateTime::createFromFormat('d-m-Y', $input['appontment_date']);
    $appDate = $dateObj ? $dateObj->format('Y-m-d') : null;

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

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

    if ($insert_id) {

        // Dynamic placeholders for template
        $placeholders = [
            'patient_name'    => $data['patient_name'],
            'patient_mobile'  => $data['patient_mobile'],
            'patient_email'   => $data['patient_email'],
            'patient_age'     => $data['patient_age'],
            'doctor_name'     => $data['doctor_name'],
            'department'      => $data['appointment_dept'],
            'date'            => date('d-m-Y', strtotime($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',
        ];

        // Appointment data table rows
        $table_rows = '
          <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Doctor</strong></td><td style="padding:10px;border:1px solid #dde;">{doctor_name}</td></tr>
          <tr><td style="padding:10px;border:1px solid #dde;"><strong>Department</strong></td><td style="padding:10px;border:1px solid #dde;">{department}</td></tr>
          <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Date</strong></td><td style="padding:10px;border:1px solid #dde;">{date}</td></tr>
          <tr><td style="padding:10px;border:1px solid #dde;"><strong>Time</strong></td><td style="padding:10px;border:1px solid #dde;">{time}</td></tr>
          <tr style="background:#f0f6ff;"><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><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('appointment');
        if ($settings) {
            if (!empty($settings->from_email)) $from_email = $settings->from_email;
            if (!empty($settings->to_emails)) $to_email = $settings->to_emails;
        }

        // ========== Patient Email (DB Template ID = 1 for Appointment) ==========
        $patient_tpl = $this->email_format_model->get_by_id(1);
        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 {
            // Fallback agar template DB mein nahi hai
            $p_subject = "Appointment Confirmation - Synergy Hospital";
            $p_body    = $this->buildEmailBody(
                'Dear <strong>' . htmlspecialchars($data['patient_name']) . '</strong>, your appointment has been booked successfully.',
                'Our team will confirm shortly. 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 (DB Template ID = 1 for Appointment) ==========
        $admin_tpl = $this->admin_email_format_model->get_by_id(1);
        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 Appointment Booking - " . $data['patient_name'];
            $a_body    = $this->buildEmailBody(
                'New appointment received from <strong>' . htmlspecialchars($data['patient_name']) . '</strong>.',
                'Please log in to admin panel to confirm.',
                $table_rows
            );
        }
        $this->sendMail($from_email, $to_email, $a_subject, $a_body);

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