<?php
require_once __DIR__ . '/../db.php';



$perPage = 30;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $perPage;

$search = trim($_GET['search'] ?? '');
$letter = trim($_GET['letter'] ?? '');

$allowedStatuses = ['pending', 'potvrdjeno', 'otkazano'];

function getSurname($fullName) {
    $parts = preg_split('/\s+/', trim($fullName));
    return count($parts) > 1 ? end($parts) : $fullName;
}

// QUICK ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $imePrezime = trim($_POST['ime_prezime'] ?? '');
        $status = $_POST['status'] ?? 'pending';
        $brojZvanica = max(1, (int)($_POST['broj_zvanica'] ?? 1));
        $nosioc = (int)($_POST['nosioc'] ?? 1);
        $nosiocId = !empty($_POST['nosioc_id']) ? (int)$_POST['nosioc_id'] : null;

        if ($imePrezime !== '' && in_array($status, $allowedStatuses, true)) {
            if ($nosioc === 1) {
                $nosiocId = null;
            }

            $stmt = $pdo->prepare("
                INSERT INTO zvanice (ime_prezime, status, broj_zvanica, nosioc, nosioc_id)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$imePrezime, $status, $brojZvanica, $nosioc, $nosiocId]);
        }
    }

    if ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $imePrezime = trim($_POST['ime_prezime'] ?? '');
        $status = $_POST['status'] ?? 'pending';
        $brojZvanica = max(1, (int)($_POST['broj_zvanica'] ?? 1));
        $nosioc = (int)($_POST['nosioc'] ?? 1);
        $nosiocId = !empty($_POST['nosioc_id']) ? (int)$_POST['nosioc_id'] : null;

        if ($id > 0 && $imePrezime !== '' && in_array($status, $allowedStatuses, true)) {
            if ($nosioc === 1) {
                $nosiocId = null;
            }

            $stmt = $pdo->prepare("
                UPDATE zvanice
                SET ime_prezime = ?, status = ?, broj_zvanica = ?, nosioc = ?, nosioc_id = ?
                WHERE id = ?
            ");
            $stmt->execute([$imePrezime, $status, $brojZvanica, $nosioc, $nosiocId, $id]);
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM zvanice WHERE id = ? OR nosioc_id = ?");
            $stmt->execute([$id, $id]);
        }
    }

    if ($action === 'delete_all') {
        $pdo->exec("DELETE FROM zvanice");
    }

    if ($action === 'confirm_all') {
        $pdo->exec("UPDATE zvanice SET status = 'potvrdjeno'");
    }

    header("Location: zvanice.php");
    exit;
}

// NOSIOCI ZA SELECT
$nosiociStmt = $pdo->query("
    SELECT id, ime_prezime 
    FROM zvanice 
    WHERE nosioc = 1 
    ORDER BY SUBSTRING_INDEX(ime_prezime, ' ', -1), ime_prezime
");
$nosioci = $nosiociStmt->fetchAll();

// FILTERI
$where = [];
$params = [];

if ($search !== '') {
    $where[] = "z.ime_prezime LIKE ?";
    $params[] = '%' . $search . '%';
}

if ($letter !== '') {
    $where[] = "SUBSTRING(SUBSTRING_INDEX(z.ime_prezime, ' ', -1), 1, 1) = ?";
    $params[] = $letter;
}

$whereSql = '';
if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

// COUNT
$countSql = "
    SELECT COUNT(*)
    FROM zvanice z
    LEFT JOIN zvanice n ON z.nosioc_id = n.id
    $whereSql
";

$countStmt = $pdo->prepare($countSql);
$countStmt->execute($params);
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, ceil($totalRows / $perPage));

// DATA
$dataSql = "
    SELECT z.*, n.ime_prezime AS nosioc_ime
    FROM zvanice z
    LEFT JOIN zvanice n ON z.nosioc_id = n.id
    $whereSql
    ORDER BY 
        SUBSTRING_INDEX(z.ime_prezime, ' ', -1) ASC,
        z.ime_prezime ASC
    LIMIT $perPage OFFSET $offset
";

$stmt = $pdo->prepare($dataSql);
$stmt->execute($params);
$zvanice = $stmt->fetchAll();

$letters = ['A','B','C','Č','Ć','D','DŽ','Đ','E','F','G','H','I','J','K','L','LJ','M','N','NJ','O','P','R','S','Š','T','U','V','Z','Ž'];
?>
<!DOCTYPE html>
<html lang="bs">
<head>
    <meta charset="UTF-8">
    <title>CMS zvanice</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            color: #111;
        }

        .admin-wrapper {
            max-width: 1300px;
            margin: 0 auto;
            padding: 25px;
        }

        h1 {
            margin-bottom: 20px;
        }

        .top-actions,
        .add-box,
        .search-box,
        .letters,
        .pagination {
            background: #fff;
            padding: 18px;
            border-radius: 14px;
            margin-bottom: 18px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.04);
        }

        input,
        select,
        button {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }

        button {
            cursor: pointer;
            background: #111;
            color: #fff;
            border-color: #111;
        }

        .danger {
            background: #b00020;
            border-color: #b00020;
        }

        .success {
            background: #087f5b;
            border-color: #087f5b;
        }

        .letters a {
            display: inline-flex;
            width: 36px;
            height: 36px;
            align-items: center;
            justify-content: center;
            text-decoration: none;
            color: #111;
            border: 1px solid #ddd;
            border-radius: 8px;
            margin: 3px;
            background: #fff;
            font-size: 13px;
        }

        .letters a.active {
            background: #111;
            color: #fff;
        }

        .table-box {
            background: #fff;
            border-radius: 14px;
            overflow-x: auto;
            box-shadow: 0 5px 25px rgba(0,0,0,0.04);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1000px;
        }

        th,
        td {
            padding: 12px;
            border-bottom: 1px solid #eee;
            text-align: left;
            vertical-align: middle;
        }

        th {
            background: #fafafa;
            font-size: 13px;
            text-transform: uppercase;
        }

        td input,
        td select {
            width: 100%;
        }

        .badge {
            display: inline-block;
            padding: 5px 9px;
            border-radius: 20px;
            font-size: 12px;
        }

        .badge.pending {
            background: #fff3cd;
        }

        .badge.potvrdjeno {
            background: #d3f9d8;
        }

        .badge.otkazano {
            background: #ffe3e3;
        }

        .pagination a {
            display: inline-block;
            padding: 8px 12px;
            margin: 3px;
            border: 1px solid #ddd;
            border-radius: 8px;
            color: #111;
            text-decoration: none;
            background: #fff;
        }

        .pagination a.active {
            background: #111;
            color: #fff;
        }

        .inline-form {
            display: contents;
        }

        .mobile-card {
            display: none;
        }

        @media (max-width: 768px) {
            .admin-wrapper {
                padding: 15px;
            }

            .table-box {
                display: none;
            }

            .mobile-card {
                display: block;
                background: #fff;
                padding: 15px;
                border-radius: 14px;
                margin-bottom: 14px;
                box-shadow: 0 5px 25px rgba(0,0,0,0.04);
            }

            .mobile-card input,
            .mobile-card select,
            .mobile-card button {
                width: 100%;
                margin-bottom: 8px;
            }

            .top-actions form {
                margin-bottom: 8px;
            }

            .top-actions button,
            .search-box input,
            .search-box button,
            .add-box input,
            .add-box select,
            .add-box button {
                width: 100%;
                margin-bottom: 8px;
            }
        }
    </style>
</head>
<body>

<div class="admin-wrapper">

    <h1>CMS zvanice</h1>

    <div class="top-actions">
        <form method="POST" style="display:inline-block;" onsubmit="return confirm('Sigurno želiš obrisati sve zvanice?');">
            <input type="hidden" name="action" value="delete_all">
            <button type="submit" class="danger">Obriši sve</button>
        </form>

        <form method="POST" style="display:inline-block;" onsubmit="return confirm('Staviti sve zvanice u potvrđeno?');">
            <input type="hidden" name="action" value="confirm_all">
            <button type="submit" class="success">Stavi sve u potvrđeno</button>
        </form>
    </div>

    <div class="add-box">
        <form method="POST">
            <input type="hidden" name="action" value="add">

            <input type="text" name="ime_prezime" placeholder="Ime i prezime" required>

            <select name="status">
                <option value="pending">Pending</option>
                <option value="potvrdjeno">Potvrđeno</option>
                <option value="otkazano">Otkazano</option>
            </select>

            <input type="number" name="broj_zvanica" value="1" min="1" placeholder="Broj zvanica">

            <select name="nosioc">
                <option value="1">Nosioc</option>
                <option value="0">Pratilac</option>
            </select>

            <select name="nosioc_id">
                <option value="">Bez nosioca</option>
                <?php foreach ($nosioci as $n): ?>
                    <option value="<?php echo $n['id']; ?>">
                        <?php echo htmlspecialchars($n['ime_prezime']); ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit">Dodaj</button>
        </form>
    </div>

    <div class="search-box">
        <form method="GET">
            <input 
                type="text" 
                name="search" 
                placeholder="Pretraga po imenu ili prezimenu" 
                value="<?php echo htmlspecialchars($search); ?>"
            >
            <button type="submit">Pretraži</button>
            <a href="zvanice.php" style="margin-left:10px;">Reset</a>
        </form>
    </div>

    <div class="letters">
        <a href="zvanice.php" class="<?php echo $letter === '' ? 'active' : ''; ?>">Sve</a>

        <?php foreach ($letters as $l): ?>
            <a 
                href="?letter=<?php echo urlencode($l); ?>" 
                class="<?php echo $letter === $l ? 'active' : ''; ?>"
            >
                <?php echo $l; ?>
            </a>
        <?php endforeach; ?>
    </div>

    <p>Ukupno rezultata: <strong><?php echo $totalRows; ?></strong></p>

    <div class="table-box">
        <table>
            <thead>
                <tr>
                    <th>Ime i prezime</th>
                    <th>Status</th>
                    <th>Broj</th>
                    <th>Tip</th>
                    <th>Nosioc</th>
                    <th>Trenutni status</th>
                    <th>Akcije</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($zvanice as $z): ?>
                    <tr>
                        <form method="POST" class="inline-form">
                            <input type="hidden" name="action" value="update">
                            <input type="hidden" name="id" value="<?php echo $z['id']; ?>">

                            <td>
                                <input type="text" name="ime_prezime" value="<?php echo htmlspecialchars($z['ime_prezime']); ?>">
                            </td>

                            <td>
                                <select name="status">
                                    <option value="pending" <?php echo $z['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="potvrdjeno" <?php echo $z['status'] === 'potvrdjeno' ? 'selected' : ''; ?>>Potvrđeno</option>
                                    <option value="otkazano" <?php echo $z['status'] === 'otkazano' ? 'selected' : ''; ?>>Otkazano</option>
                                </select>
                            </td>

                            <td>
                                <input type="number" name="broj_zvanica" value="<?php echo (int)$z['broj_zvanica']; ?>" min="1">
                            </td>

                            <td>
                                <select name="nosioc">
                                    <option value="1" <?php echo (int)$z['nosioc'] === 1 ? 'selected' : ''; ?>>Nosioc</option>
                                    <option value="0" <?php echo (int)$z['nosioc'] === 0 ? 'selected' : ''; ?>>Pratilac</option>
                                </select>
                            </td>

                            <td>
                                <select name="nosioc_id">
                                    <option value="">Bez nosioca</option>
                                    <?php foreach ($nosioci as $n): ?>
                                        <option 
                                            value="<?php echo $n['id']; ?>"
                                            <?php echo (int)$z['nosioc_id'] === (int)$n['id'] ? 'selected' : ''; ?>
                                        >
                                            <?php echo htmlspecialchars($n['ime_prezime']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>

                            <td>
                                <span class="badge <?php echo htmlspecialchars($z['status']); ?>">
                                    <?php echo htmlspecialchars($z['status']); ?>
                                </span>
                            </td>

                            <td>
                                <button type="submit">Sačuvaj</button>
                        </form>

                        <form method="POST" style="display:inline;" onsubmit="return confirm('Obrisati ovu zvanicu?');">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?php echo $z['id']; ?>">
                            <button type="submit" class="danger">Obriši</button>
                        </form>
                            </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php foreach ($zvanice as $z): ?>
        <div class="mobile-card">
            <form method="POST">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?php echo $z['id']; ?>">

                <input type="text" name="ime_prezime" value="<?php echo htmlspecialchars($z['ime_prezime']); ?>">

                <select name="status">
                    <option value="pending" <?php echo $z['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="potvrdjeno" <?php echo $z['status'] === 'potvrdjeno' ? 'selected' : ''; ?>>Potvrđeno</option>
                    <option value="otkazano" <?php echo $z['status'] === 'otkazano' ? 'selected' : ''; ?>>Otkazano</option>
                </select>

                <input type="number" name="broj_zvanica" value="<?php echo (int)$z['broj_zvanica']; ?>" min="1">

                <select name="nosioc">
                    <option value="1" <?php echo (int)$z['nosioc'] === 1 ? 'selected' : ''; ?>>Nosioc</option>
                    <option value="0" <?php echo (int)$z['nosioc'] === 0 ? 'selected' : ''; ?>>Pratilac</option>
                </select>

                <select name="nosioc_id">
                    <option value="">Bez nosioca</option>
                    <?php foreach ($nosioci as $n): ?>
                        <option 
                            value="<?php echo $n['id']; ?>"
                            <?php echo (int)$z['nosioc_id'] === (int)$n['id'] ? 'selected' : ''; ?>
                        >
                            <?php echo htmlspecialchars($n['ime_prezime']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit">Sačuvaj</button>
            </form>

            <form method="POST" onsubmit="return confirm('Obrisati ovu zvanicu?');">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?php echo $z['id']; ?>">
                <button type="submit" class="danger">Obriši</button>
            </form>
        </div>
    <?php endforeach; ?>

    <div class="pagination">
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <a 
                class="<?php echo $i === $page ? 'active' : ''; ?>"
                href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&letter=<?php echo urlencode($letter); ?>"
            >
                <?php echo $i; ?>
            </a>
        <?php endfor; ?>
    </div>

</div>

</body>
</html>