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

class HK_Webhook {

    public function __construct() {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes() {
        register_rest_route('hallo-ketua/v1', '/webhook', [
            'methods' => 'POST',
            'callback' => [$this, 'handle_webhook'],
            'permission_callback' => '__return_true'
        ]);
    }

    public function handle_webhook($request) {
        $json = $request->get_body();
        $data = json_decode($json);

        if (!$data || !isset($data->message, $data->from)) {
            return new WP_REST_Response(['error' => 'Invalid data'], 400);
        }

        $message = trim($data->message);
        $from = $data->from;
        $ketua_wa = get_option('hk_ketua_whatsapp');

        // Only process messages from ketua
        if ($from !== $ketua_wa) {
            return new WP_REST_Response(['status' => 'ignored'], 200);
        }

        // Check if message contains ID
        if (preg_match('/ID:\s*(PROPOSAL|APPOINTMENT)-(\d+)/i', $message, $matches)) {
            $type = strtolower($matches[1]);
            $id = $matches[2];

            // Get the decision (1 or 2)
            if (preg_match('/^[12]$/', trim($message))) {
                $decision = trim($message);
                $this->handle_decision($type, $id, $decision, $from);
            }
        }
        // Check if this is a reason response (after approved)
        else {
            $this->check_pending_reason($from, $message);
        }

        return new WP_REST_Response(['status' => 'success'], 200);
    }

    private function handle_decision($type, $id, $decision, $from) {
        global $wpdb;

        if ($decision == '1') {
            // Ask for reason
            $wpdb->update(
                $wpdb->prefix . "hk_{$type}s",
                ['status' => 'waiting_reason'],
                ['id' => $id]
            );

            update_option("hk_waiting_reason_{$type}_{$id}", $from);

            $message = "Terima kasih! Boleh kasih alasan mengapa diterima?";
            HK_StarSender::send_message($from, $message);
        } else {
            // Reject directly
            $table = $wpdb->prefix . "hk_{$type}s";
            $wpdb->update($table, ['status' => 'rejected'], ['id' => $id]);

            HK_StarSender::send_message($from, "Berhasil ditolak.");
        }
    }

    private function check_pending_reason($from, $message) {
        global $wpdb;

        // Check proposals
        $proposal = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}hk_proposals WHERE status = 'waiting_reason' ORDER BY id DESC LIMIT 1"
        ));

        if ($proposal && get_option("hk_waiting_reason_proposal_{$proposal->id}") === $from) {
            $wpdb->update(
                $wpdb->prefix . 'hk_proposals',
                [
                    'status' => 'approved',
                    'alasan_keputusan' => $message
                ],
                ['id' => $proposal->id]
            );

            delete_option("hk_waiting_reason_proposal_{$proposal->id}");
            HK_StarSender::notify_user($proposal->whatsapp, 'proposal', 'approved', $message);
            HK_StarSender::send_message($from, "Proposal berhasil disetujui!");
            return;
        }

        // Check appointments
        $appointment = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}hk_appointments WHERE status = 'waiting_reason' ORDER BY id DESC LIMIT 1"
        ));

        if ($appointment && get_option("hk_waiting_reason_appointment_{$appointment->id}") === $from) {
            $wpdb->update(
                $wpdb->prefix . 'hk_appointments',
                [
                    'status' => 'approved',
                    'alasan_keputusan' => $message
                ],
                ['id' => $appointment->id]
            );

            delete_option("hk_waiting_reason_appointment_{$appointment->id}");
            HK_StarSender::notify_user($appointment->whatsapp, 'appointment', 'approved', $message);
            HK_StarSender::send_message($from, "Janji temu berhasil disetujui!");
            return;
        }
    }
}
