<?php
session_start();
include "config.php";

// Redirect if user not logged in
if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

$user = $_SESSION['user'];
$pid = $user['pid'];
$uid = $user['id'];

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    // Required IDs
    $id = isset($_POST['cdr_id']) ? (int) $_POST['cdr_id'] : 0;
    $data_ids_json = $_POST['data_ids'] ?? '[]';

    // Decode JSON
    $data_ids = json_decode($data_ids_json, true);

    if ($id === 0 || !is_array($data_ids) || count($data_ids) === 0) {
        echo "<script>alert('Invalid data.'); window.location.href='cdr.php';</script>";
        exit();
    }

    // Escape JSON
    $cdr_id_escaped = mysqli_real_escape_string($con, json_encode($data_ids));

    // ✅ UPDATE query (NO INSERT)
    $query = "
        UPDATE cdr 
        SET cdr_id = '$cdr_id_escaped'
        WHERE id = $id
    ";

    if (mysqli_query($con, $query)) {
        echo "<script>alert('CDR updated successfully.'); window.location.href='cdr.php';</script>";
    } else {
        echo "<script>alert('Update failed.'); window.location.href='cdr.php';</script>";
    }

    mysqli_close($con);
} else {
    echo "<script>window.location.href='cdr.php';</script>";
    exit();
}
?>