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

class HK_StarSender {

    private static $api_url = 'https://api.starsender.online/api/send';

    // Normalize WhatsApp number to consistent format
    private static function normalize_whatsapp($number) {
        // Remove all non-numeric characters
        $number = preg_replace('/[^0-9]/', '', $number);

        // Convert 628xxx to 08xxx
        if (substr($number, 0, 2) === '62') {
            $number = '0' . substr($number, 2);
        }

        return $number;
    }

    public static function send_message($to, $body, $messageType = 'text', $file = null) {
        $data = [
            'messageType' => $messageType,
            'to' => $to,
            'body' => $body
        ];

        if ($file) $data['file'] = $file;

        $response = wp_remote_post(self::$api_url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => HK_API_KEY
            ],
            'body' => json_encode($data),
            'timeout' => 30
        ]);

        if (is_wp_error($response)) {
            error_log('StarSender Error: ' . $response->get_error_message());
            return false;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        return $body['success'] ?? false;
    }

    public static function send_otp($whatsapp) {
        global $wpdb;

        // Normalize WhatsApp number
        $whatsapp = self::normalize_whatsapp($whatsapp);

        $otp = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));

        // Delete old OTP
        $wpdb->delete($wpdb->prefix . 'hk_otp', ['whatsapp' => $whatsapp]);

        // Insert new OTP
        $inserted = $wpdb->insert($wpdb->prefix . 'hk_otp', [
            'whatsapp' => $whatsapp,
            'otp' => $otp,
            'expires_at' => $expires
        ]);

        if (!$inserted) {
            error_log("Failed to insert OTP: " . $wpdb->last_error);
            return ['success' => false];
        }

        $message = "Kode OTP Anda: *{$otp}*\nBerlaku 10 menit.";
        $sent = self::send_message($whatsapp, $message);

        // Return debug info (remove in production)
        return [
            'success' => true,
            'otp' => $otp,
            'whatsapp' => $whatsapp
        ];
    }

    public static function verify_otp($whatsapp, $otp) {
        global $wpdb;

        // Normalize WhatsApp number
        $whatsapp = self::normalize_whatsapp($whatsapp);
        $otp = trim($otp);

        $record = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}hk_otp WHERE whatsapp = %s AND otp = %s AND verified = 0 AND expires_at > NOW() ORDER BY id DESC LIMIT 1",
            $whatsapp, $otp
        ));

        if (!$record) {
            return false;
        }

        $wpdb->update($wpdb->prefix . 'hk_otp', ['verified' => 1], ['id' => $record->id]);
        return true;
    }

    public static function notify_ketua_proposal($proposal_id) {
        $ketua_wa = get_option('hk_ketua_whatsapp');
        if (!$ketua_wa) return false;

        global $wpdb;
        $proposal = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}hk_proposals WHERE id = %d", $proposal_id));
        if (!$proposal) return false;

        $message = "*PROPOSAL BARU*\n\n";
        $message .= "Lembaga: {$proposal->lembaga}\n";
        $message .= "PJ: {$proposal->penanggung_jawab}\n";
        $message .= "Event: {$proposal->event_detail}\n";
        $message .= "Jumlah: {$proposal->jumlah}\n";
        $message .= "Kapan: {$proposal->kapan}\n\n";
        $message .= "Balas *1* untuk terima\n";
        $message .= "Balas *2* untuk tolak\n";
        $message .= "ID: PROPOSAL-{$proposal_id}";

        return self::send_message($ketua_wa, $message);
    }

    public static function notify_ketua_appointment($appointment_id) {
        $ketua_wa = get_option('hk_ketua_whatsapp');
        if (!$ketua_wa) return false;

        global $wpdb;
        $apt = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}hk_appointments WHERE id = %d", $appointment_id));
        if (!$apt) return false;

        $message = "*JANJI TEMU BARU*\n\n";
        $message .= "Nama: {$apt->nama}\n";
        $message .= "Keperluan: {$apt->keperluan}\n";
        $message .= "Waktu: " . date('d/m/Y H:i', strtotime($apt->tanggal_jam)) . "\n\n";
        $message .= "Balas *1* untuk terima\n";
        $message .= "Balas *2* untuk tolak\n";
        $message .= "ID: APPOINTMENT-{$appointment_id}";

        return self::send_message($ketua_wa, $message);
    }

    public static function notify_user($whatsapp, $type, $status, $alasan = '') {
        $status_text = $status === 'approved' ? 'DITERIMA' : 'DITOLAK';
        $type_text = $type === 'proposal' ? 'Proposal' : 'Janji Temu';

        $message = "*{$type_text} {$status_text}*\n\n";
        if ($status === 'approved' && $alasan) {
            $message .= "Alasan: {$alasan}\n\n";
        }
        $message .= "Terima kasih.";

        return self::send_message($whatsapp, $message);
    }
}
