<?php

require_once "config.php"; 
header('Content-Type: application/json'); 

$method = $_SERVER['REQUEST_METHOD']; 

error_reporting(E_ALL);
ini_set('display_errors', 1);

switch ($method) {
    case 'GET': 
        $query = "SELECT cFileImage, ckode, cnama, cbarcode FROM tbbarang";

        if ($stmt = $conn->prepare($query)) {
            $stmt->execute(); 
            $result = $stmt->get_result(); 
            $data = $result->fetch_all(MYSQLI_ASSOC); 

            if (empty($data)) {
                echo json_encode(array("message" => "No data found"));
            } else {
                $notFoundData = []; 

                foreach ($data as &$item) {
                    if (!empty($item['cFileImage'])) {
                        $headers = get_headers($item['cFileImage'], 1); 
                        
                        if ($headers && strpos($headers[0], "200") !== false) {
                            $item['image_status'] = "200 OK"; 
                        } else {
                            $item['image_status'] = "404 Not Found";
                            $notFoundData[] = $item;
                        }
                    } else {
                        $item['image_status'] = "No URL"; 
                    }
                }

                echo json_encode($notFoundData); 
            }

            $stmt->close();
        } else {
            echo json_encode(array("error" => "Failed to prepare the SQL query"));
        }
        break;

    default:
        echo json_encode(array("error" => "Invalid request method"));
        break;
}

mysqli_close($conn);
?>
