<?php
if (!defined('ABSPATH')) exit;

class HK_Appointment {

    public function __construct() {
        add_action('wp_ajax_hk_submit_appointment', [$this, 'submit_appointment']);
        add_action('wp_ajax_nopriv_hk_submit_appointment', [$this, 'submit_appointment']);
    }

    public function submit_appointment() {
        check_ajax_referer('hk_appointment_nonce', 'nonce');

        $whatsapp = sanitize_text_field($_POST['whatsapp'] ?? '');
        $token = sanitize_text_field($_POST['token'] ?? '');

        if (!wp_verify_nonce($token, 'hk_verified_' . $whatsapp)) {
            wp_send_json_error(['message' => 'Invalid verification']);
        }

        global $wpdb;
        $inserted = $wpdb->insert($wpdb->prefix . 'hk_appointments', [
            'whatsapp' => $whatsapp,
            'nama' => sanitize_text_field($_POST['nama'] ?? ''),
            'keperluan' => sanitize_textarea_field($_POST['keperluan'] ?? ''),
            'tanggal_jam' => sanitize_text_field($_POST['tanggal_jam'] ?? ''),
            'status' => 'pending'
        ]);

        if ($inserted) {
            $appointment_id = $wpdb->insert_id;
            HK_StarSender::notify_ketua_appointment($appointment_id);
            wp_send_json_success(['message' => 'Appointment submitted successfully', 'id' => $appointment_id]);
        } else {
            wp_send_json_error(['message' => 'Failed to submit appointment']);
        }
    }
}
