<?php
require dirname( dirname(__FILE__) ).'/api/Prozigzig.php';
$h = new Prozigzig();
header('Content-type: text/json');

// Wrap everything in try-catch
try {
    // Step 1: Get JSON input
    $data = json_decode(file_get_contents('php://input'), true);

    // Step 2: Validate inputs
    $parcel_id = $data['parcel_id'] ?? '';
    $new_status = $data['status'] ?? '';

    if (empty($parcel_id) || empty($new_status)) {
        throw new Exception("Required parameters missing!", 401);
    }

    // Step 3: Get UID from parcel
    $parcel = $h->queryfire("SELECT uid FROM tbl_parcel WHERE id = $parcel_id");
    if (!$parcel) {
        throw new Exception("Parcel query failed", 500);
    }

    $parcelRow = $parcel->fetch_assoc();
    if (!$parcelRow) {
        throw new Exception("Parcel not found!", 404);
    }

    $uid = $parcelRow['uid'];

    // Step 4: Update parcel status
    $table = "tbl_parcel";
    $field = ['status' => $new_status];
    $where = "WHERE id = $parcel_id";
    $h->updateData_Api($field, $table, $where);

    // Step 5: Get user name
    $user = $h->queryfire("SELECT name FROM tbl_user WHERE id = $uid");
    if (!$user) {
        throw new Exception("User query failed", 500);
    }

    $udata = $user->fetch_assoc();
    $name = $udata['name'] ?? 'User';

    // Step 6: Get OneSignal credentials
    $setting = $h->queryfire("SELECT one_key, one_hash FROM tbl_setting WHERE id = 1");
    if (!$setting) {
        throw new Exception("Settings query failed", 500);
    }

    $set = $setting->fetch_assoc();
    if (empty($set['one_key']) || empty($set['one_hash'])) {
        throw new Exception("Missing OneSignal credentials", 500);
    }

    // Step 7: Prepare OneSignal payload
    $content = [
        "en" => $name . ', Your Parcel #' . $parcel_id . ' Status Updated to ' . $new_status . '.'
    ];
    $heading = [
        "en" => "Parcel Status Updated!"
    ];

    $fields = [
        'app_id' => $set['one_key'],
        'included_segments' => ["Active Users"],
        'filters' => [
            ['field' => 'tag', 'key' => 'user_id', 'relation' => '=', 'value' => $uid]
        ],
        'contents' => $content,
        'headings' => $heading
    ];
    $fieldsJson = json_encode($fields);

    // Step 8: Send push notification
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic ' . $set['one_hash']
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsJson);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        throw new Exception("OneSignal Error: $error", 500);
    }

    // Success response
    echo json_encode([
        "ResponseCode" => "200",
        "Result" => "true",
        "ResponseMsg" => "Parcel status updated successfully!"
    ]);
} catch (Exception $e) {
    // Return safe structured error
    http_response_code($e->getCode() ?: 500);
    echo json_encode([
        "ResponseCode" => (string)($e->getCode() ?: 500),
        "Result" => "false",
        "ResponseMsg" => $e->getMessage()
    ]);
}
