<?php
/**
 * Rig N Dig - Mobile API v1 / Certificate Verification
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';
require_once '../api_helper.php';

$sn = sanitize($_GET['sn'] ?? '');

if (!$sn) {
    apiResponse(false, 'Serial number required');
}

try {
    $cert = Database::fetchOne("
        SELECT c.*, i.invoice_number 
        FROM certificates c 
        LEFT JOIN invoices i ON c.invoice_id = i.id 
        WHERE c.serial_number = ? OR c.id = ?
    ", [$sn, (int)$sn]);

    if ($cert) {
        $cert['file_url'] = SITE_URL . '/uploads/' . $cert['file_path'];
        $cert['verification_hash'] = md5($cert['id'] . APP_SECRET);
        apiResponse(true, 'Certificate verified', $cert);
    } else {
        apiResponse(false, 'Certificate not found or invalid');
    }
} catch (Exception $e) {
    apiResponse(false, 'Verification failed');
}
