<?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

try {
    // Fetch data
    $stmt = $pdo->prepare("SELECT id, co_id, acc_name FROM accounts WHERE co_id = :sel_co AND acc_categ='warehouse' ORDER BY id ASC LIMIT 1");
    $stmt->execute(['sel_co' => $sel_co]); 
    $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'])
        ]);
    } else {
        echo json_encode(['store_location' => "No data found"]);
    }
} catch (Exception $e) {
    error_log("Database error in get_def_acc.php: " . $e->getMessage());
    echo json_encode(['store_location' => 'An error occurred. Please try again later.']);
}
?>
