<?php
/* 
----------------------------------------------------------
  MODULE :  AJAX RECORD DELETE 
  V2.0 / 2025
  AUTHOR : SGHAIER MAHMOUD  
  FEATURES :
  - Single delete (legacy mode)
  - Multiple delete (comma-separated encrypted IDs)
  - Safe numeric validation
----------------------------------------------------------
*/

require_once(__DIR__.'/../ssinclude/app-init.php');
require_once(__DIR__.'/../ssinclude/app-session.php');

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// GET values
$id     = verif_get('id');        // encrypted ID or comma list
$tbl    = verif_get('tbl');       // table name
$tblid  = verif_get('tblkey');    // primary key name

if (!empty($id) && !empty($tbl) && !empty($tblid)) {

    // 🔹 Split comma-separated IDs
    $id_list_enc = explode(",", $id);
    $id_list_dec = [];

    // 🔹 Decrypt & validate each ID
    foreach ($id_list_enc as $enc_value) {
        $dec = decrypt_data($enc_value);  // decrypt

        if (is_numeric($dec)) {
            $id_list_dec[] = intval($dec); // keep only valid numbers
        }
    }

    // 🔹 If at least one valid ID exists
    if (!empty($id_list_dec)) {

        try {
            // Convert to SQL-safe IN() string
            $in = implode(",", $id_list_dec);

            // Multiple or single delete — both handled here
            $sql = "DELETE FROM `$tbl` WHERE `$tblid` IN ($in);";

            $affectedRows = $db->exec($sql);

            // Success response (same as legacy)
            if (isset($affectedRows)) {
                echo "1";
            }

        } catch (PDOException $e) {
            // Error response (same as legacy)
            echo "0";
        }
    }
}

require_once(__DIR__.'/../ssinclude/app-close.php');
?>
