<?php
error_reporting(E_ALL);  
ini_set('display_errors', 1);  

require_once "../../includes/db.php";
header('Content-Type: application/json');
session_start(['read_and_close' => true]);

// Validate and sanitize input
if (!isset($_GET['sel_co']) || !is_numeric($_GET['sel_co'])) {
    echo json_encode(['error' => "Invalid request"]);
    exit;
}

$sel_co = (int) $_GET['sel_co']; // Cast to integer
$ttype = $_GET['ttype'];
//$ttype2 = $_GET['ttype2'];

try {
    // Fetch data
    $stmt = $pdo->prepare("SELECT id, co_id, form, starting_No, gen_status FROM doc_no_generator WHERE co_id = :sel_co AND form=:ttype  ORDER BY id ASC LIMIT 1");
    $stmt->execute([':sel_co' => $sel_co,':ttype' => $ttype]); 
    $store = $stmt->fetch(PDO::FETCH_ASSOC);

    // Debugging: Log and print raw query result
    error_log("Debug - Fetched Data: " . print_r($store, true));

   if ($store) {
        echo json_encode([
            'store_location' => htmlspecialchars($store['id']),
            'comp_id' => htmlspecialchars($store['co_id']),
            'form' => htmlspecialchars($store['form']),
            'gen_status' => htmlspecialchars($store['gen_status'])
        ]);
    } else {
        echo json_encode(['store_location' => "No data found"]);
    }
} catch (Exception $e) {
    error_log("Database error in get_doc_no_settings.php: " . $e->getMessage());
    echo json_encode(['store_location' => 'An error occurred. Please try again later.']);
}
?>
