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

class Save_Appointment extends CI_Controller {

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

   public function index()
{
    // print_r('123');
    // die();
    // exit();
    
    header("Access-Control-Allow-Origin: https://synergy.jeetinfo.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;
    }

//         $data = [
            $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) {
            echo json_encode([
                'status' => 'success',
                'message' => 'Appointment booked successfully',
                'id' => $insert_id
            ]);
        } else {
            echo json_encode([
                'status' => 'error',
                'message' => 'Failed to save appointment'
            ]);
        }
    }
}
