<?php
ob_start();
header('Content-Type: text/html; charset=utf-8');
require_once 'db_connect.php';
require_once 'includes/ProxyHelper.php';
include 'includes/header.php';

$proxy = new ProxyHelper();
$results = null;
$error = null;
$debugLog = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bookNo = $_POST['book_no'] ?? '';
    $pageNo = $_POST['page_no'] ?? '';
    $year = $_POST['year'] ?? '';
    
    // API Endpoints from up cod-1.txt
    $tryUrls = [
        'https://bdris.gov.bd/api/br/book/search',
        'https://bdris.gov.bd/api/br/book/list/by-office'
    ];

    $params = [];
    if ($bookNo) $params['bookNumber'] = $bookNo;
    if ($pageNo) $params['pageNumber'] = $pageNo;
    if ($year) $params['year'] = $year;
    // Default pagination params
    $params['page'] = 0;
    $params['size'] = 20;

    foreach ($tryUrls as $url) {
        // Try POST with JSON
        $response = $proxy->fetch($url, 'POST', $params, true, 'https://bdris.gov.bd/');
        
        $status = $response['status'] ?? 0;
        $body = $response['body'] ?? '';
        
        $debugLog[] = [
            'url' => $url,
            'status' => $status,
            'len' => strlen($body)
        ];

        if ($status === 200) {
            // Check if login page or error
            if (stripos($body, '<title>Login</title>') === false && stripos($body, 'login-page') === false) {
                $data = $proxy->parseJson($response);
                if ($data) {
                    $results = $data;
                    break;
                }
            }
        }
    }

    if (!$results) {
        if (isset($response) && stripos($response['body'] ?? '', '<title>Login</title>') !== false) {
             $error = 'BDRIS সেশন পাওয়া যায়নি। অনুগ্রহ করে অটো কানেক্ট বা কুকি আপডেট করুন।';
        } else {
             $error = 'তথ্য পাওয়া যায়নি বা সার্ভার রেসপন্স করেনি। (HTTP ' . ($response['status'] ?? 0) . ')';
        }
    }
}
?>

<div class="row justify-content-center">
    <div class="col-md-10">
        <div class="card mt-4">
            <div class="card-header bg-success text-white">
                <h4 class="mb-0"><i class="fas fa-book"></i> জন্ম নিবন্ধন বই অনুসন্ধান</h4>
            </div>
            <div class="card-body">
                <form action="" method="POST" class="row g-3">
                    <div class="col-md-4">
                        <label for="year" class="form-label">নিবন্ধনের বছর</label>
                        <input type="number" class="form-control" id="year" name="year" value="<?php echo htmlspecialchars($_POST['year'] ?? ''); ?>" placeholder="YYYY">
                    </div>
                    <div class="col-md-4">
                        <label for="book_no" class="form-label">বই নম্বর</label>
                        <input type="text" class="form-control" id="book_no" name="book_no" value="<?php echo htmlspecialchars($_POST['book_no'] ?? ''); ?>">
                    </div>
                    <div class="col-md-4">
                        <label for="page_no" class="form-label">পাতা নম্বর</label>
                        <input type="text" class="form-control" id="page_no" name="page_no" value="<?php echo htmlspecialchars($_POST['page_no'] ?? ''); ?>">
                    </div>
                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-success"><i class="fas fa-search"></i> অনুসন্ধান করুন</button>
                    </div>
                </form>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="alert alert-danger mt-3"><?php echo $error; ?></div>
        <?php endif; ?>

        <?php if ($results): ?>
            <div class="card mt-4">
                <div class="card-header bg-light">
                    <h5 class="mb-0">অনুসন্ধানের ফলাফল</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th>নিবন্ধন নম্বর</th>
                                    <th>নাম (বাংলা)</th>
                                    <th>নাম (ইংরেজি)</th>
                                    <th>জন্ম তারিখ</th>
                                    <th>পিতার নাম</th>
                                    <th>মাতার নাম</th>
                                    <th>বই-পাতা</th>
                                    <th>অ্যাকশন</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $list = $results['data'] ?? ($results['content'] ?? []);
                                // Handle if single object
                                if (isset($list['ubrn'])) $list = [$list];
                                
                                foreach ($list as $row): 
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['ubrn'] ?? $row['birthRegistrationNumber'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($row['personNameBn'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($row['personNameEn'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($row['personBirthDate'] ?? $row['dob'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($row['fatherNameBn'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($row['motherNameBn'] ?? ''); ?></td>
                                    <td>
                                        <small class="d-block text-muted">বই: <?php echo htmlspecialchars($row['bookNumber'] ?? '-'); ?></small>
                                        <small class="d-block text-muted">পাতা: <?php echo htmlspecialchars($row['pageNumber'] ?? '-'); ?></small>
                                    </td>
                                    <td>
                                        <form action="search-birth.php" method="POST" target="_blank">
                                            <input type="hidden" name="birth_reg_no" value="<?php echo htmlspecialchars($row['ubrn'] ?? $row['birthRegistrationNumber'] ?? ''); ?>">
                                            <input type="hidden" name="dob" value="<?php echo htmlspecialchars($row['personBirthDate'] ?? $row['dob'] ?? ''); ?>">
                                            <button type="submit" class="btn btn-sm btn-info text-white"><i class="fas fa-eye"></i></button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if (empty($list)): ?>
                                    <tr><td colspan="8" class="text-center text-muted p-4">কোন তথ্য পাওয়া যায়নি</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php if (isset($results['totalPages']) && $results['totalPages'] > 1): ?>
                    <div class="card-footer">
                        <small class="text-muted">Total Pages: <?php echo $results['totalPages']; ?>, Total Records: <?php echo $results['totalElements'] ?? 0; ?></small>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Raw Data Debug -->
            <div class="mt-3">
                 <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#rawDebug">Show Raw Data</button>
                 <div class="collapse mt-2" id="rawDebug">
                     <div class="card card-body">
                         <pre><?php echo htmlspecialchars(json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
                     </div>
                 </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
