<?php
session_start();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

if (!isset($_SESSION['member_id'])) {
    header("Location: index.html");
    exit();
}

$member_id = $_SESSION['member_id']; 
$serverName = "10.10.1.8";
$connectionOptions = [
    "Database" => "LIBRARYDB",
    "Uid" => "sa",
    "PWD" => "kolkata@1",
    "CharacterSet" => "UTF-8"
];
$results = [];
$member_issues = []; 
$new_arrivals_grouped = [
    'English' => [],
    'Bengali' => [],
    'Hindi' => []
];
$search_performed = false;
$memberName = "Calcutta Club Member"; 

try {
    $conn = sqlsrv_connect($serverName, $connectionOptions);
    if ($conn) {
        $nameSql = "SELECT m.MNAME 
                    FROM loginmst l
                    INNER JOIN MEMBERMST m ON l.USERNAME = m.MEMNUB 
                    WHERE l.USERNAME = ?";
        
        $nameStmt = sqlsrv_query($conn, $nameSql, array($member_id));
        if ($nameStmt && $row = sqlsrv_fetch_array($nameStmt, SQLSRV_FETCH_ASSOC)) {
            $memberName = $row['MNAME'];
        }
        $arrivalSql = "SELECT Acc_No, ISBN, Book_Title, Author, 
                       CASE 
                        WHEN Language_Id = 117 THEN 'English'
                        WHEN Language_Id = 47 THEN 'Bengali'
                        WHEN Language_Id = 48 THEN 'Hindi' 
                        ELSE 'Other'
                       END AS Language_Name
                       FROM BookMaster 
                       WHERE AccDate >= DATEADD(day, -80, GETDATE())
                       ORDER BY Language_Name ASC, AccDate DESC";
        $arrivalStmt = sqlsrv_query($conn, $arrivalSql);
        if ($arrivalStmt) {
            while ($arrivalRow = sqlsrv_fetch_array($arrivalStmt, SQLSRV_FETCH_ASSOC)) {
                $lang = $arrivalRow['Language_Name'];
                if (isset($new_arrivals_grouped[$lang])) {
                    $new_arrivals_grouped[$lang][] = $arrivalRow;
                }
            }
        }
        if (isset($_GET['get_records'])) {
            $search_performed = true;
            $authorSearch = trim($_GET['author'] ?? '');
            $titleSearch = trim($_GET['title'] ?? '');
            $langSearch = $_GET['language'] ?? '';
            if (!empty($authorSearch) || !empty($titleSearch) || !empty($langSearch)) {
                $tsql = "SELECT B.Acc_No, B.ISBN, B.Author, B.Book_Title, B.Year_Pub, B.Subject, B.VolumeNo, B.Edition, B.Tag
                         FROM BookMaster B WHERE 1=1";            
                $params = [];
                if (!empty($authorSearch)) {
                    $tsql .= " AND (B.Author LIKE ? OR B.Second_Author LIKE ?)";
                    $params[] = "%$authorSearch%"; $params[] = "%$authorSearch%";
                }
                if (!empty($titleSearch)) {
                    $tsql .= " AND B.Book_Title LIKE ?";
                    $params[] = "%$titleSearch%";
                }           
                if ($langSearch == '117') {
                    $tsql .= " AND B.Language_Id = 117";
                } elseif ($langSearch == '47') {
                    $tsql .= " AND B.Language_Id = 47";
                }
                $tsql .= " ORDER BY B.Book_Title ASC";
                $stmt = sqlsrv_query($conn, $tsql, $params);
                if($stmt) {
                    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                        $results[] = $row;
                    }
                }
            }
        }
        $issueSql = "SELECT B.Acc_No, B.ISBN, B.Book_Title, B.Author, I.Issue_Dt, I.Pro_Ret_Dt 
                     FROM BookIssueMaster I
                     JOIN BookMaster B ON I.Acc_no = B.Acc_No
                     WHERE I.Memnub = ? AND (I.Act_Ret_Dt IS NULL OR I.Act_Ret_Dt = '')";    
        $issueStmt = sqlsrv_query($conn, $issueSql, array($member_id));
        if ($issueStmt) {
            while ($issueRow = sqlsrv_fetch_array($issueStmt, SQLSRV_FETCH_ASSOC)) {
                $member_issues[] = $issueRow;
            }
        }
        sqlsrv_close($conn);
    }
} catch (Exception $e) { }

function getMagImage($name) {
    $filename = strtolower(str_replace([' ', '&', "'"], ['_', 'and', ''], $name)) . ".jpg";
    return "PHOTOS/" . $filename;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Member Portal | Calcutta Club Library</title>
    <script type="text/javascript">
        window.onpageshow = function(event) {
            if (event.persisted) { window.location.reload(); }
        };
    </script>

    <style>
        :root { 
            --primary: #1e293b; 
            --accent: #4a90e2; 
            --bg: #f8fafc; 
            --white: #ffffff;
            --text-muted: #64748b;
            --success: #10b981;
            --danger: #e11d48;
            --warning: #f59e0b;
        }
        body { font-family: 'Segoe UI', system-ui, sans-serif; margin: 0; background: var(--bg); color: #334155; line-height: 1.6; }       
        .navbar { background-color: #263c5fff !important; padding: 0 40px; height: 70px; display: flex; justify-content: space-between; align-items: center; color: white; position: sticky; top: 0; z-index: 1000; box-shadow: 0 4px 12px rgba(52, 32, 235, 0.51); }
        .nav-brand { display: flex; align-items: center; gap: 12px; }
        .nav-brand img { height: 40px; }
        .nav-brand span { font-weight: 700; font-size: 1.2em; letter-spacing: 0.5px; }
        .nav-links { display: flex; gap: 2px; }
        .nav-btn { background: transparent; color: whitesmoke; border: none; padding: 24px 16px; cursor: pointer; font-size: 13px; font-weight: 600; transition: 0.2s; border-bottom: 3px solid transparent; }
        .nav-btn:hover { color: white; background: rgba(255,255,255,0.05); }
        .nav-btn.active { color: white; border-bottom-color: var(--accent); background: rgba(255,255,255,0.05); }
        .container { padding: 40px 20px; max-width: 1200px; margin: auto; }
        .tab-content { display: none; animation: fadeIn 0.3s ease-out; }
        .tab-content.active { display: block; }

        #about {
            position: relative;
            padding: 40px 20px;
            border-radius: 12px;
            overflow: hidden; 
        }
        #about::before {
            content: "";
            position: absolute;
            top: 0; 
            left: 0;
            width: 100%; 
            height: 100%;
            background: linear-gradient(rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.45)), 
                        url('PHOTOS/CCL_Library.JPG'); 
            background-size: 100% 100%; 
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: local; 
            opacity: 1; 
            z-index: -1;
        }
        #about h2 {
            color: #ffffff !important;
            text-shadow: 0px 2px 10px rgba(0, 0, 0, 0.8), 0px 4px 20px rgba(0, 0, 0, 0.5); 
            position: relative;
            font-size: 2rem;
            margin-bottom: 30px;
        }

        @keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
        .manual-grid { display: flex; flex-wrap: wrap; gap: 20px; margin-top: 20px; justify-content: center; }
        .manual-card { 
            background: var(--white); 
            padding: 25px; 
            border-radius: 12px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.05); 
            border: 1px solid #e2e8f0; 
            transition: transform 0.2s;
            flex: 0 1 calc(33.333% - 14px); 
            min-width: 280px; 
            box-sizing: border-box;
            min-height: 200px;
            cursor: pointer;
        }
        .manual-card:hover { transform: translateY(-5px); border-color: var(--accent); background-color: #f1f5f9; }
        .manual-card h3 { color: var(--accent); margin: 0 0 12px 0; font-size: 18px; display: flex; align-items: center; gap: 10px; }
        .manual-card p { font-size: 14px; margin: 0; color: #475569; }
        .book-cover { width: 45px; height: 65px; object-fit: cover; border-radius: 4px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); background: #e2e8f0; }
        .title-cell { display: flex; align-items: center; gap: 12px; }
        .status-pill { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; text-transform: uppercase; }
        .status-available { background: #dcfce7; color: #166534; }
        .status-issued { background: #fee2e2; color: #991b1b; }  
        .table-wrapper { 
            background: var(--white); 
            border-radius: 12px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.05); 
            max-height: 700px; 
            overflow: auto; 
            margin-bottom: 30px; 
            border: 1px solid #e2e8f0;
            -webkit-overflow-scrolling: touch;
        }
        .results-table { width: 100%; border-collapse: separate; border-spacing: 0; }
        .results-table th { 
            background: #f1f5f9; 
            color: var(--primary); 
            font-size: 12px; 
            text-transform: uppercase; 
            padding: 18px 20px; 
            text-align: left; 
            border-bottom: 2px solid #e2e8f0; 
            position: sticky; 
            top: 0; 
            z-index: 100; 
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .results-table td { padding: 12px 20px; border-bottom: 1px solid #f1f5f9; font-size: 14px; }    
        .profile-header { background: var(--white); padding: 30px; border-radius: 12px; margin-bottom: 30px; border-left: 6px solid var(--accent); box-shadow: 0 4px 15px rgba(0,0,0,0.03); }
        .search-container { position: sticky; top: 70px; z-index: 999; margin-bottom: 30px; transition: all 0.3s ease; }
        .search-area { 
            background: var(--primary); 
            padding: 25px; 
            border-radius: 12px; 
            display: flex; 
            gap: 15px; 
            align-items: flex-end; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transition: max-height 0.4s ease, padding 0.4s ease, opacity 0.3s ease;
            overflow: hidden;
            max-height: 500px; 
        }
        .search-area.collapsed { max-height: 0; padding-top: 0; padding-bottom: 0; opacity: 0; pointer-events: none; }       
        .toggle-search-btn {
            position: absolute;
            bottom: -20px;
            left: 50%;
            transform: translateX(-50%);
            background: var(--accent);
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            cursor: pointer;
            box-shadow: 0 4px 10px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            z-index: 1001;
            transition: transform 0.3s ease;
        }
        .toggle-search-btn.up { transform: translateX(-50%) rotate(180deg); }
        .input-group input, .input-group select { padding: 12px; border-radius: 6px; border: 1px solid #334155; background: #1e293b; color: white; width: 100%; box-sizing: border-box; }
        .btn-search { background: var(--accent); color: white; border: none; padding: 0 35px; border-radius: 6px; cursor: pointer; font-weight: 700; height: 45px; }
        .notice-box { 
            background-color: #fffbeb; 
            border: 1px solid #fef3c7; 
            padding: 15px 20px; 
            border-radius: 8px; 
            margin-bottom: 30px; 
            display: flex; 
            align-items: center; 
            gap: 12px; 
            box-shadow: 0 2px 8px rgba(245, 158, 11, 0.1);
        }
        .notice-text { font-size: 14px; color: #92400e; font-weight: 600; }
        .status-badge { padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: 700; }
        .status-ok { background: #dcfce7; color: #166534; }
        .status-late { background: #fee2e2; color: #991b1b; }
        .timings-grid { display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; }
        .timing-detail-card { 
            background: var(--white); 
            flex: 1; 
            min-width: 300px; 
            border-radius: 16px; 
            padding: 30px; 
            text-align: center; 
            border: 1px solid #e2e8f0; 
            box-shadow: 0 4px 20px rgba(0,0,0,0.04);
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            transition: transform 0.2s ease;
        }
        .timing-detail-card:hover { 
            transform: translateY(-5px); 
            border-color: var(--accent); 
            box-shadow: 0 8px 25px rgba(0,0,0,0.08); 
        }
        .timing-icon { font-size: 32px; background: #f1f5f9; width: 70px; height: 70px; display: flex; align-items: center; justify-content: center; border-radius: 50%; color: var(--accent); }
        .timing-day { font-weight: 800; font-size: 1.2em; color: var(--primary); margin-top: 10px; }
        .timing-hours { font-size: 1.5em; font-weight: 900; color: var(--accent); }
        .timing-off { color: var(--danger) !important; }
        .language-header { background: #f1f5f9; padding: 12px 25px; border-bottom: 1px solid #e2e8f0; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 1px; font-size: 14px; border-radius: 12px 12px 0 0; }
        .mag-section { background: var(--white); border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-bottom: 30px; overflow: hidden; border: 1px solid #e2e8f0; }
        .mag-section-header { background: #f1f5f9; padding: 15px 25px; border-bottom: 1px solid #e2e8f0; font-weight: 800; color: var(--primary); text-transform: uppercase; letter-spacing: 1px; font-size: 14px; }
        .mag-list { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1px; background: #e2e8f0; }
        .mag-item { background: var(--white); padding: 15px 25px; display: flex; justify-content: space-between; align-items: center; font-size: 14px; }
        .mag-info { display: flex; align-items: center; gap: 5px; }
        .mag-name { font-weight: 600; color: #334155; }
        .mag-num { color: var(--text-muted); font-weight: 700; margin-right: 15px; width: 30px; display: inline-block; }
        .mag-freq { color: var(--text-muted); font-size: 10px; font-weight: 800; background: #f1f5f9; padding: 2px 8px; border-radius: 4px; text-transform: uppercase; }
        .mag-gift { font-size: 10px; background: #fef3c7; color: #92400e; padding: 2px 6px; border-radius: 4px; margin-left: 8px; font-weight: 800; }
        .mag-lang-header { grid-column: span 2; background: #f8fafc; padding: 10px 25px; font-size: 11px; font-weight: 900; color: #94a3b8; letter-spacing: 2px; border-bottom: 1px solid #e2e8f0; }
        .credit-badge { margin-top: 20px; padding-top: 25px; border-top: 1px solid rgba(255, 255, 255, 0.3); text-align: center; color: #ffffff !important; font-size: 13px; font-weight: 700; position: relative; z-index : 10; text-shadow: 0px 1px 5px rgba(0, 0, 0, 0.9); display:block; width: 100%; }

        @media (max-width: 768px) {
            .navbar { flex-direction: column; height: auto; padding: 15px; gap: 15px; } 
            .nav-links { flex-wrap: wrap; justify-content: center; gap: 5px; }  
            .nav-btn { padding: 10px 12px; font-size: 11px; }
            .container { padding: 15px 10px; min-height: calc(100vh - 150px); }
            .search-container { position: relative; top: 0; margin-bottom: 40px; }
            .search-area { flex-direction: column; align-items: stretch; }
            .manual-card, .timing-detail-card { flex: 1 1 100% !important; min-width: 0 !important; }
            .table-wrapper { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
            .results-table { min-width: 420px; }
            .results-table th, .results-table td { padding: 10px 8px; font-size: 11px; }
            .book-cover { width: 30px; height: 45px; }
            .title-cell { gap: 8px; }
            .title-cell div { max-width: 140px; white-space: normal; word-wrap: break-word; line-height: 1.2; }
            .mag-list { grid-template-columns: 1fr !important; }
            .mag-lang-header { grid-column: span 1 !important; text-align: center; padding: 12px; }
            .mag-item { padding: 15px 20px; flex-wrap: wrap; gap: 8px; }
            .mag-name { font-size: 13px; }
            #about { padding: 30px 15px; }
            #about h2 { font-size: 1.5rem; }
        }
    </style>
</head>
<body>
<nav class="navbar">
    <div class="nav-brand">
        <img src="PHOTOS/Logo.png" alt="Logo">
        <span>CALCUTTA CLUB LTD.</span>
    </div>
    <div class="nav-links">
        <button class="nav-btn <?php echo (!$search_performed) ? 'active' : ''; ?>" onclick="openTab(event, 'about')">About Us</button>
        <button class="nav-btn" onclick="openTab(event, 'arrivals')">New Arrivals</button>
        <button class="nav-btn" onclick="openTab(event, 'magazines')">Magazines</button>
        <button class="nav-btn <?php echo ($search_performed) ? 'active' : ''; ?>" onclick="openTab(event, 'search')">Books Available</button>
        <button class="nav-btn" onclick="openTab(event, 'profile')">My Details</button>
        <button class="nav-btn" onclick="openTab(event, 'timings')">Library Timings</button>
        <button class="nav-btn" onclick="location.href='logout.php'" style="color: #fb7185;">Logout</button>
    </div>
</nav>
<div class="container">
    <div id="about" class="tab-content <?php echo (!$search_performed) ? 'active' : ''; ?>">
        <h2 style="margin-top:0;">Application User Manual</h2>
        <div class="manual-grid">
            <div class="manual-card" onclick="openTab(event, 'arrivals')">
                <h3>📚 Browsing New Arrivals</h3>
                <p>Visit the 'New Arrivals' tab to see books added recently, categorized by Language.</p>
            </div>
            <div class="manual-card" onclick="openTab(event, 'search')">
                <h3>🔍 Searching for Books</h3>
                <p>Use the 'Books Available' tab to search by Author, Title, or Language. Check real-time availability.</p>
            </div>
            <div class="manual-card" onclick="openTab(event, 'profile')">
                <h3>👤 Managing Your Profile</h3>
                <p>The 'My Details' tab shows your currently issued books, return due dates, and overdue alerts.</p>
            </div>
            <div class="manual-card" onclick="openTab(event, 'magazines')">
                <h3>📰 Periodicals</h3>
                <p>Check the 'Magazines' tab for a complete list of Indian and Foreign magazines and newspapers.</p>
            </div>
            <div class="manual-card" onclick="openTab(event, 'timings')">
                <h3>🕒 Library Timings</h3>
                <p>Check the 'Library Timings' tab to see the detailed schedule and weekly off-days.</p>
            </div>
        </div>
        <div class="credit-badge">Powered by Calcutta Club IT Team | Developer: Mr. Srayoan Ray</div>
    </div>
    <div id="arrivals" class="tab-content">
        <h2 style="margin-top:0; color:var(--primary);">New Book Additions</h2>
        <?php 
        $found_any = false;
        foreach ($new_arrivals_grouped as $language => $books): 
            if (!empty($books)): 
                $found_any = true;
        ?>
            <div class="language-header"><?php echo $language; ?> Books</div>
            <div class="table-wrapper">
                <table class="results-table">
                    <thead><tr><th style="width: 60%;">Book Title</th><th>Author</th></tr></thead>
                    <tbody>
                        <?php foreach ($books as $book): ?>
                            <tr>
                                <td class="title-cell">
                                    <img src="PHOTOS/book.jpg" data-isbn="<?php echo htmlspecialchars($book['ISBN'] ?? ''); ?>" class="book-cover internet-cover" alt="Cover" loading="lazy">
                                    <div style="font-weight:700; color:var(--accent);"><?php echo htmlspecialchars($book['Book_Title']); ?></div>
                                </td>
                                <td><?php echo htmlspecialchars($book['Author']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; endforeach; 
        if (!$found_any): ?>
            <div class="table-wrapper"><div style="text-align:center; padding:40px; color:var(--text-muted);">No new arrivals found for the past 80 days.</div></div>
        <?php endif; ?>
    </div>
    <div id="magazines" class="tab-content">
        <h2 style="margin-top:0; color:var(--primary);">Periodicals & Reading Material</h2>
        <div class="mag-section">
            <div class="mag-section-header">Indian Magazines</div>
            <div class="mag-list">
                <?php 
                $indian = [
                    ["BUSINESS WORLD", "FORTNIGHTLY"], ["DESH", "WEEKLY"], ["EPW", "FORTNIGHTLY"],
                    ["FEMINA", "FORTNIGHTLY"], ["FRONTLINE", "MONTHLY"], ["INDIA TODAY", "WEEKLY"],
                    ["READER'S DIGEST", "FORTNIGHTLY"], ["SANANDA", "MONTHLY"], ["SAPTAHIK BARTAMAN", "WEEKLY"],
                    ["THE WEEK", "WEEKLY"], ["PRABUDDHA BHARATA", "MONTHLY", true], ["THE VEDANTA KESARI", "MONTHLY", true]
                ];
                foreach ($indian as $idx => $m): ?>
                <div class="mag-item">
                    <div class="mag-info">
                        <span class="mag-num"><?php echo $idx + 1; ?>.</span>
                        <img src="<?php echo getMagImage($m[0]); ?>" class="book-cover" onerror="this.src='PHOTOS/book.jpg'">
                        <span class="mag-name"><?php echo $m[0]; ?><?php echo isset($m[2]) ? ' <span class="mag-gift">Gift</span>' : ''; ?></span>
                    </div>
                    <span class="mag-freq"><?php echo $m[1]; ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="mag-section">
            <div class="mag-section-header">Foreign Magazines</div>
            <div class="mag-list">
                <?php 
                $foreign = [["ECONOMIST", "WEEKLY"], ["WOMEN & HOME", "MONTHLY"], ["NATIONAL GEOGRAPHIC", "MONTHLY"]];
                foreach ($foreign as $idx => $m): ?>
                <div class="mag-item">
                    <div class="mag-info">
                        <span class="mag-num"><?php echo $idx + 1; ?>.</span>
                        <img src="<?php echo getMagImage($m[0]); ?>" class="book-cover" onerror="this.src='PHOTOS/book.jpg'">
                        <span class="mag-name"><?php echo $m[0]; ?></span>
                    </div>
                    <span class="mag-freq"><?php echo $m[1]; ?></span>
                </div>
                <?php endforeach; ?>
                <div class="mag-item" style="background:transparent;"></div>
            </div>
        </div>
        <div class="mag-section">
            <div class="mag-section-header">Newspapers</div>
            <div class="mag-list">
                <div class="mag-lang-header">ENGLISH</div>
                <?php 
                $eng_papers = ["THE STATESMAN", "INDIAN EXPRESS", "BUSINESS STANDARD", "THE ECONOMIC TIMES", "THE TIMES OF INDIA", "THE TELEGRAPH", "THE HINDU", "MINT"];
                foreach ($eng_papers as $idx => $n): ?>
                <div class="mag-item">
                    <div class="mag-info">
                        <span class="mag-num"><?php echo $idx + 1; ?>.</span>
                        <img src="<?php echo getMagImage($n); ?>" class="book-cover" onerror="this.src='PHOTOS/book.jpg'">
                        <span class="mag-name"><?php echo $n; ?></span>
                    </div>
                </div>
                <?php endforeach; ?>             
                <div class="mag-lang-header">HINDI</div>
                <div class="mag-item">
                    <div class="mag-info">
                        <span class="mag-num">1.</span>
                        <img src="PHOTOS/sanmarg.jpg" class="book-cover" onerror="this.src='PHOTOS/book.jpg'">
                        <span class="mag-name">SANMARG</span>
                    </div>
                </div>
                <div class="mag-item" style="background:transparent;"></div>             
                <div class="mag-lang-header">BENGALI</div>
                <?php 
                $ben_papers = ["ANANDA BAZAR PATRIKA", "EI SAMAY"];
                foreach ($ben_papers as $idx => $n): ?>
                <div class="mag-item">
                    <div class="mag-info">
                        <span class="mag-num"><?php echo $idx + 1; ?>.</span>
                        <img src="<?php echo getMagImage($n); ?>" class="book-cover" onerror="this.src='PHOTOS/book.jpg'">
                        <span class="mag-name"><?php echo $n; ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <div id="search" class="tab-content <?php echo ($search_performed) ? 'active' : ''; ?>">
        <div class="search-container">
            <form method="GET">
                <div class="search-area" id="searchArea">
                    <div class="input-group" style="flex:1;">
                        <label style="color:#94a3b8; font-size:11px; font-weight:700; text-transform:uppercase;">Author</label>
                        <input type="text" name="author" value="<?php echo htmlspecialchars($_GET['author'] ?? ''); ?>">
                    </div>
                    <div class="input-group" style="flex:1;">
                        <label style="color:#94a3b8; font-size:11px; font-weight:700; text-transform:uppercase;">Title</label>
                        <input type="text" name="title" value="<?php echo htmlspecialchars($_GET['title'] ?? ''); ?>">
                    </div>
                    <div class="input-group" style="flex:1;">
                        <label style="color:#94a3b8; font-size:11px; font-weight:700; text-transform:uppercase;">Language</label>
                        <select name="language">
                            <option value="">All Languages</option>
                            <option value="117" <?php if(isset($_GET['language']) && $_GET['language'] == '117') echo 'selected'; ?>>English</option>
                            <option value="47" <?php if(isset($_GET['language']) && $_GET['language'] == '47') echo 'selected'; ?>>Bengali</option>
                        </select>
                    </div>
                    <button type="submit" name="get_records" class="btn-search">Search</button>
                </div>
            </form>
            <button type="button" class="toggle-search-btn" id="toggleSearchBtn" onclick="toggleSearchArea()">^</button>
        </div>
        <div class="table-wrapper">
            <?php if ($search_performed && !empty($results)): ?>
                <table class="results-table">
                    <thead><tr><th>Acc_No</th><th>ISBN</th><th>Author</th><th>Book Title</th><th>Year <br>Of Publication</th><th>Vol</th><th>Ed</th><th>Subject</th><th>Remarks</th></tr></thead>
                    <tbody>
                        <?php foreach ($results as $row): ?>
                            <tr>
                                <td style="font-weight:600; color:var(--text-muted);"><?php echo htmlspecialchars($row['Acc_No']); ?></td>
                                <td><?php echo htmlspecialchars($row['ISBN']); ?></td>
                                <td><?php echo htmlspecialchars($row['Author']); ?></td>
                                <td class="title-cell">
                                    <img src="PHOTOS/book.jpg" data-isbn="<?php echo htmlspecialchars($row['ISBN'] ?? ''); ?>" class="book-cover internet-cover" alt="Cover" loading="lazy">
                                    <div style="font-weight:700; color:var(--accent);"><?php echo htmlspecialchars($row['Book_Title']); ?></div>
                                </td>
                                <td><?php echo htmlspecialchars($row['Year_Pub']); ?></td>
                                <td><?php echo htmlspecialchars($row['VolumeNo']); ?></td>
                                <td><?php echo htmlspecialchars($row['Edition']); ?></td>
                                <td><?php echo htmlspecialchars($row['Subject']); ?></td>
                                <td><?php echo (trim($row['Tag']) === 'I') ? '<span class="status-pill status-issued">Issued</span>' : '<span class="status-pill status-available">Available</span>'; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div style="padding:60px; text-align:center; color:var(--text-muted);"><?php echo $search_performed ? "No records found." : "Enter search criteria to view available books."; ?></div>
            <?php endif; ?>
        </div>
    </div>
    <div id="profile" class="tab-content">
        <div class="profile-header">
            <div style="display:flex; justify-content:space-between;">
                <div><label style="display:block; font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase;">Member Name</label>
                <span style="font-size:20px; font-weight:700; color:var(--primary);"><?php echo htmlspecialchars($memberName); ?></span></div>
                <div><label style="display:block; font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase;">Member ID</label>
                <span style="font-size:20px; font-weight:700; color:var(--primary);"><?php echo htmlspecialchars($member_id); ?></span></div>
            </div>
        </div>
        <div class="notice-box">
            <span style="font-size:18px;">⚠️</span>
            <span class="notice-text">Please return or re-issue the issued book(s) in order to avoid unnecessary fine.</span>
        </div>
        <div class="table-wrapper">
            <div style="padding:20px 25px; border-bottom:1px solid #f1f5f9; font-weight:700; color:var(--primary);">Currently Issued Books</div>
            <table class="results-table">
                <thead><tr><th>Book Title</th><th>Author</th><th>Issue Date</th><th>Return Due Date</th><th>Status / Days Left</th></tr></thead>
                <tbody>
                    <?php if (!empty($member_issues)): 
                        $today = new DateTime(); $today->setTime(0,0,0);
                        foreach ($member_issues as $issue): 
                            $dueDate = ($issue['Pro_Ret_Dt'] instanceof DateTime) ? $issue['Pro_Ret_Dt'] : new DateTime($issue['Pro_Ret_Dt']);
                            $dueDate->setTime(0,0,0);
                            $interval = $today->diff($dueDate);
                            $days = $interval->days;
                            $isOverdue = ($today > $dueDate && $days > 0);
                    ?>
                        <tr>
                            <td class="title-cell">
                                <img src="PHOTOS/book.jpg" data-isbn="<?php echo htmlspecialchars($issue['ISBN'] ?? ''); ?>" class="book-cover internet-cover" alt="Cover" loading="lazy">
                                <div style="font-weight:600;"><?php echo htmlspecialchars($issue['Book_Title']); ?></div>
                            </td>
                            <td><?php echo htmlspecialchars($issue['Author']); ?></td>
                            <td><?php echo ($issue['Issue_Dt'] instanceof DateTime) ? $issue['Issue_Dt']->format('d-M-Y') : $issue['Issue_Dt']; ?></td>
                            <td><?php echo $dueDate->format('d-M-Y'); ?></td>
                            <td>
                                <?php if ($isOverdue): ?>
                                    <span class="status-badge status-late">Overdue: <?php echo $days; ?> Days</span>
                                <?php else: ?>
                                    <span class="status-badge status-ok"><?php echo ($today == $dueDate) ? "Due Today" : $days . " Days Left"; ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; else: ?>
                        <tr><td colspan="5" style="text-align:center; padding:40px; color:var(--text-muted);">No books currently issued.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div id="timings" class="tab-content">
        <h2 style="margin-top:0; color:var(--primary); text-align:center; margin-bottom:40px;">Library Schedule & Hours</h2>
        <div class="timings-grid">
            <div class="timing-detail-card" style="border-top: 5px solid var(--danger);">
                <div class="timing-icon" style="color:var(--danger);">🚫</div>
                <div class="timing-day">Monday</div>
                <div class="timing-hours timing-off">Weekly Offday</div>
                <p style="font-size:13px; color:var(--text-muted);">The library remains closed on Monday every week.</p>
            </div>
            <div class="timing-detail-card" style="border-top: 5px solid #f59e0b; background-color: #fffbeb;">
                <div class="timing-icon" style="color: #f59e0b; background-color: #fef3c7;">🕒</div>
                <div class="timing-day">Tuesday to Saturday</div>
                <div class="timing-hours" style="color: #92400e;">10:00 AM — 09:00 PM</div>
                <p style="font-size:13px; color: #b45309;">Full library services are available.</p>
            </div>
            <div class="timing-detail-card" style="border-top: 5px solid var(--accent);">
                <div class="timing-icon">✨</div>
                <div class="timing-day">Sunday</div>
                <div class="timing-hours">12:00 PM — 02:00 PM</div>
                <p style="font-size:13px; color:var(--text-muted);">Limited hours for members.</p>
            </div>
            <div class="timing-detail-card" style="flex-basis: 100%; text-align: left; align-items: flex-start;">
                <div style="display:flex; gap:15px; align-items:center;">
                    <div class="timing-icon" style="color:var(--warning); font-size:24px; width:50px; height:50px;">ℹ️</div>
                    <h3 style="margin:0;">Important Notes</h3>
                </div>
                <ul style="font-size:14px; color:var(--text-muted); margin-top:15px; padding-left:20px;">
                    <li>Please ensure books are returned 15 minutes before closing time.</li>
                    <li>Online browsing is available 24/7 via this portal.</li>
                    <li>Library timings are subject to change on National Holidays.</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
function openTab(evt, tabName) {
    var i, tabcontent, navbtn;
    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; tabcontent[i].classList.remove("active"); }
    navbtn = document.getElementsByClassName("nav-btn");
    for (i = 0; i < navbtn.length; i++) { navbtn[i].classList.remove("active"); }
    document.getElementById(tabName).style.display = "block";
    document.getElementById(tabName).classList.add("active");
    evt.currentTarget.classList.add("active");
}
function toggleSearchArea() {
    const searchArea = document.getElementById('searchArea');
    const toggleBtn = document.getElementById('toggleSearchBtn');
    searchArea.classList.toggle('collapsed');
    toggleBtn.classList.toggle('up');
}
document.addEventListener("DOMContentLoaded", function() {
    if (window.innerWidth <= 768 && <?php echo $search_performed ? 'true' : 'false'; ?>) {
        const searchArea = document.getElementById('searchArea');
        const toggleBtn = document.getElementById('toggleSearchBtn');
        searchArea.classList.add('collapsed');
        toggleBtn.classList.add('up');
    }
    const covers = document.querySelectorAll('.internet-cover');
    const defaultImage = 'PHOTOS/book.jpg';   
    covers.forEach(img => {
        let rawIsbn = img.getAttribute('data-isbn');
        if (!rawIsbn) { img.src = defaultImage; return; }
        let isbn = rawIsbn.replace(/[- ]/g, "");
        if (isbn.length < 10) { img.src = defaultImage; return; }
        let isbn10 = (isbn.length === 13) ? convertISBN13to10(isbn) : isbn;
        const amazonUrl = `https://images-na.ssl-images-amazon.com/images/P/${isbn10}.01._SCLZZZZZZZ_.jpg`;
        img.src = amazonUrl;
        img.onload = function() { if (this.naturalWidth <= 1) { runFallbacks(this, isbn); } };
        img.onerror = function() { runFallbacks(this, isbn); };
    });
    function runFallbacks(element, isbn) {
        fetch(`https://www.googleapis.com/books/v1/volumes?q=isbn:${isbn}`)
            .then(response => response.json())
            .then(data => {
                if (data.items && data.items[0].volumeInfo.imageLinks) {
                    element.src = data.items[0].volumeInfo.imageLinks.thumbnail.replace('http:', 'https:');
                } else {
                    element.src = `https://covers.openlibrary.org/b/isbn/${isbn}-M.jpg?default=false`;
                }
            })
            .catch(() => { element.src = 'PHOTOS/book.jpg'; });
        element.onerror = function() { this.src = 'PHOTOS/book.jpg'; this.onerror = null; };
    }
    function convertISBN13to10(isbn13) {
        let isbn10 = isbn13.substring(3, 12);
        let sum = 0;
        for (let i = 0; i < 9; i++) { sum += parseInt(isbn10[i]) * (10 - i); }
        let checkDigit = 11 - (sum % 11);
        if (checkDigit === 10) checkDigit = 'X';
        else if (checkDigit === 11) checkDigit = '0';
        return isbn10 + checkDigit;
    }
});
</script>
</body>
</html>