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

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

class Save_Estimate extends CI_Controller {
    
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Get_An_Estimate_Model', 'estimate');
        $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');
        $this->load->library('upload');
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST");
        header("Access-Control-Allow-Headers: Content-Type");

        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;
        }
    }

    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()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
            return;
        }

        $data = [
            'patient_name'   => $this->input->post('patient_name'),
            'patient_mobile' => $this->input->post('patient_mobile'),
            'patient_email'  => $this->input->post('patient_email'),
            'patient_age'    => $this->input->post('patient_age'),
            'patient_gender' => $this->input->post('patient_gender'),
            'decription'     => $this->input->post('decription'),
            'status'         => $this->input->post('status') ?: 0,
            'publish'        => $this->input->post('publish') ?: 1,
        ];

        $upload_path = './uploads/';
        if (!is_dir($upload_path)) mkdir($upload_path, 0777, true);

        if (!empty($_FILES['latest_report']['name'])) {
            $config = ['upload_path' => $upload_path, 'allowed_types' => 'pdf|jpg|jpeg|png|doc|docx', 'max_size' => 10240, 'encrypt_name' => true];
            $this->upload->initialize($config);
            if ($this->upload->do_upload('latest_report')) {
                $data['latest_report'] = $this->upload->data()['file_name'];
            }
        }

        if (!empty($_FILES['last_medical_prescription']['name'])) {
            $config = ['upload_path' => $upload_path, 'allowed_types' => 'pdf|jpg|jpeg|png|doc|docx', 'max_size' => 10240, 'encrypt_name' => true];
            $this->upload->initialize($config);
            if ($this->upload->do_upload('last_medical_prescription')) {
                $data['last_medical_prescription'] = $this->upload->data()['file_name'];
            }
        }

        $insert_id = $this->estimate->save($data);
        
        if ($insert_id) {

            $placeholders = [
                'patient_name'   => $data['patient_name'],
                'patient_mobile' => $data['patient_mobile'],
                'patient_email'  => $data['patient_email'],
                'patient_age'    => $data['patient_age'],
                'patient_gender' => $data['patient_gender'],
                '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>Name</strong></td><td style="padding:10px;border:1px solid #dde;">{patient_name}</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>Age</strong></td><td style="padding:10px;border:1px solid #dde;">{patient_age}</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);

            if (!empty($data['latest_report'])) {
                $report_url = base_url('uploads/' . $data['latest_report']);
                $table_rows .= '
              <tr style="background:#f0f6ff;"><td style="padding:10px;border:1px solid #dde;"><strong>Latest Report</strong></td><td style="padding:10px;border:1px solid #dde;"><a href="' . $report_url . '" target="_blank" style="color:#003773;text-decoration:underline;">Download Report</a></td></tr>';
            }
            if (!empty($data['last_medical_prescription'])) {
                $prescription_url = base_url('uploads/' . $data['last_medical_prescription']);
                $table_rows .= '
              <tr><td style="padding:10px;border:1px solid #dde;"><strong>Prescription</strong></td><td style="padding:10px;border:1px solid #dde;"><a href="' . $prescription_url . '" target="_blank" style="color:#003773;text-decoration:underline;">Download Prescription</a></td></tr>';
            }

            // Fetch Email settings from database
            $from_email = 'system@synergyhospital.co.in';
            $to_email = 'shaktisinh.chudasama@synergyhospital.co.in, sursinh.barad@synergyhospital.co.in';
            $settings = $this->ens_model->get_by_form_key('estimate');
            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 = 3 for Estimate) ==========
            $patient_tpl = $this->email_format_model->get_by_id(3);
            if ($patient_tpl) {
                $p_subject = $this->replacePlaceholders($patient_tpl->subject, $placeholders);
                if (stripos($p_subject, 'appointment') !== false) {
                    $p_subject = "Get An Estimate - Synergy Hospital";
                }
                $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 = "Estimate Request Received - Synergy Hospital";
                $p_body    = $this->buildEmailBody(
                    'Dear <strong>' . htmlspecialchars($data['patient_name']) . '</strong>, we have received your estimate request.',
                    'Our team will contact you within 24-48 hours. 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 = 3 for Estimate) ==========
            $admin_tpl = $this->admin_email_format_model->get_by_id(3);
            if ($admin_tpl) {
                $a_subject = $this->replacePlaceholders($admin_tpl->subject, $placeholders);
                if (stripos($a_subject, 'appointment') !== false) {
                    $a_subject = "New Estimate Request - " . $data['patient_name'];
                }
                $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 Estimate Request - " . $data['patient_name'];
                $a_body    = $this->buildEmailBody(
                    'New estimate request 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' => 'Data saved successfully', 'id' => $insert_id]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to save data']);
        }
    }
}