<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$number_id = filter_var($_POST['number_id'] ?? 0, FILTER_VALIDATE_INT);

if (!$number_id) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid number ID']);
    exit();
}

try {
    // Check record exists
    $stmt = $pdo->prepare("SELECT id, number, order_id FROM active_number WHERE id = :id LIMIT 1");
    $stmt->bindParam(':id', $number_id, PDO::PARAM_INT);
    $stmt->execute();
    $record = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$record) {
        echo json_encode(['status' => '0', 'msg' => 'Number record not found']);
        exit();
    }

    // Delete the record
    $stmt = $pdo->prepare("DELETE FROM active_number WHERE id = :id");
    $stmt->bindParam(':id', $number_id, PDO::PARAM_INT);

    if ($stmt->execute()) {
        echo json_encode([
            'status' => '1',
            'msg'    => 'Number +' . $record['number'] . ' (Order: ' . $record['order_id'] . ') has been deleted successfully'
        ]);
    } else {
        echo json_encode(['status' => '0', 'msg' => 'Failed to delete number record']);
    }

} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
}
?>