<?php
/**
 * AlixDeal Order Notification System - PRO Edition
 */

// --- 1. DATABASE CONNECTION ---
$db_host = 'localhost';
$db_name = 'alixdeal_ads1'; 
$db_user = 'alixdeal_ads1'; 
$db_pass = 'alixdeal_ads1'; 

try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection Failed: " . $e->getMessage());
}

// --- 2. BROWSER HANDSHAKE (Only for testing) ---
if (basename($_SERVER['PHP_SELF']) == 'notify_mpwa.php') {
    echo "<body style='background:#000; color:#0f0; font-family:monospace; padding:20px;'>";
    echo "<h2>🚀 AlixDeal System Handshake...</h2>";
    $stmt = $conn->query("SELECT order_id FROM orders ORDER BY order_id DESC LIMIT 1");
    $last_order = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($last_order) {
        echo "[+] Sending Real Data Test to: 917351150482<br>";
        send_mpwa_notification($last_order['order_id'], 'placed', "917351150482");
    }
    echo "</body>";
    exit;
}

// --- 3. MAIN NOTIFICATION FUNCTION (The Real One) ---
function send_mpwa_notification($order_id, $status_type, $custom_num = null) {
    global $conn;
    
    $api_key   = "ic9mQDkIkey3hcdNGT7gGDgtZ49K"; 
    $sender_no = "918273147063"; 
    $api_url   = "https://ads.alixdeal.info/send-message"; 

    try {
        $stmt = $conn->prepare("SELECT o.*, c.whatsapp, c.username, s.service_name FROM orders o 
                                JOIN clients c ON o.client_id = c.client_id 
                                JOIN services s ON o.service_id = s.service_id 
                                WHERE o.order_id = :id");
        $stmt->execute(['id' => $order_id]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) return;

        // Number Setup
        $user_phone = ($custom_num) ? $custom_num : preg_replace('/[^0-9]/', '', $order['whatsapp']);
        if (strlen($user_phone) == 10) $user_phone = "91" . $user_phone;

        $username = $order['username'];
        $service  = $order['service_name'];
        $price    = round($order['order_charge'], 2);
        $quantity = $order['order_quantity'];

        // --- REAL MESSAGE LOGIC ---
        $header = "✨ *ALIXDEAL ORDER UPDATE* ✨\n━━━━━━━━━━━━━━━\n";
        $footer = "\n━━━━━━━━━━━━━━━\n🙏 *Shukriya!* Visit: alixdeal.shop";

        if ($status_type == 'placed') {
            $msg = $header . "🚀 *Order Placed Successfully!*\n\nHello @" . $username . ",\nAapka order receive ho gaya hai.\n\n🆔 *Order ID:* #" . $order_id . "\n🔢 *Quantity:* " . $quantity . "\n🛠️ *Service:* " . $service . "\n💰 *Total Charge:* ₹" . $price . "\n⏳ *Status:* Pending" . $footer;
        } 
        elseif ($status_type == 'completed') {
            $msg = $header . "✅ *Order Completed!*\n\nHello @" . $username . ",\nAapki service deliver ho gayi hai.\n\n🆔 *Order ID:* #" . $order_id . "\n🛠️ *Service:* " . $service . "\n✨ *Enjoy your growth!*" . $footer;
        } 
        elseif ($status_type == 'canceled') {
            $msg = $header . "❌ *Order Canceled*\n\nOrder ID: #" . $order_id . "\nKuch issue ki wajah se order cancel kar diya gaya hai. Refund process ho chuka hai." . $footer;
        } else {
            $msg = $header . "⚙️ *Order Status:* ".ucfirst($status_type)."\n\nOrder ID: #" . $order_id . "\nAapka order update ho chuka hai." . $footer;
        }

        // Send API Request
        $data = ["api_key" => $api_key, "sender" => $sender_no, "number" => $user_phone, "message" => $msg];
        $ch = curl_init($api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        $res_arr = json_decode($response, true);
        curl_close($ch);

        // Logging
        $log_status = (isset($res_arr['status']) && $res_arr['status'] == true) ? 'sent' : 'failed';
        $conn->prepare("INSERT INTO whatsapp_logs (order_id, receiver, message, status, created_at) VALUES (:oid, :rec, :msg, :st, NOW())")
             ->execute(['oid'=>$order_id, 'rec'=>$user_phone, 'msg'=>$msg, 'st'=>$log_status]);
        
        return $response;

    } catch (Exception $e) { return $e->getMessage(); }
}
?>