<?php
session_start();
if(!isset($_SESSION['autorizovan']))
    header("Location: login.php");
require_once 'db.php';

$db = new Db();



$model_pretraga = "";
$proizvodjac_pretraga = array();
$tip_pretraga = array();
$cena_do_pretraga = 0;
$godina_od_pretraga = 0;

$postoji_pretraga = false;


if(isset($_GET['logout']))
{
    setcookie("user",1,time() - 1);
    setcookie("pass",1,time() - 1);
    session_destroy();
    header("Location: login.php");
}

if (isset($_GET['search_model']) && $_GET['search_model'] != "" ) {
    $model_pretraga = $_GET['search_model'];
    $postoji_pretraga = true;
}
if (isset($_GET['search_proizvodjac']) && !empty($_GET['search_proizvodjac']) ) {
    // expect array of proizvodjac ids
    $proizvodjac_pretraga = (array) $_GET['search_proizvodjac'];
    if (count($proizvodjac_pretraga) > 0) $postoji_pretraga = true;
}
if (isset($_GET['search_tip']) && !empty($_GET['search_tip']) ) {
    // expect array of tip ids
    $tip_pretraga = (array) $_GET['search_tip'];
    if (count($tip_pretraga) > 0) $postoji_pretraga = true;
}
if (isset($_GET['search_cena_do']) &&  $_GET['search_cena_do'] != "" ) {
    $cena_do_pretraga = $_GET['search_cena_do'];
    $postoji_pretraga = true;
}
if (isset($_GET['search_godina_od']) &&  $_GET['search_godina_od'] != "" ) {
    $godina_od_pretraga = $_GET['search_godina_od'];
    $postoji_pretraga = true;
}

$automobili = $db->SpisakAutomobila($model_pretraga, $proizvodjac_pretraga, $tip_pretraga, $cena_do_pretraga, $godina_od_pretraga);
$izdvojeniAutomobili = $db->IzdvojeniAutomobili();
$prozvodjaci = $db->Proizvodjaci();
$karoserije = $db->TipoviKaroserije();

// handle sorting (simple array sort since SpisakAutomobila doesn't support ORDER BY yet)
if (isset($_GET['sort']) && $_GET['sort'] != "") {
    if ($_GET['sort'] === 'rastuce') {
        usort($automobili, function($a, $b){
            return $a['cena'] <=> $b['cena'];
        });
    } elseif ($_GET['sort'] === 'opadajuce') {
        usort($automobili, function($a, $b){
            return $b['cena'] <=> $a['cena'];
        });
    }
}

// pagination setup
$perPage = 5;
$totalItems = count($automobili);
$totalPages = ($totalItems > 0) ? ceil($totalItems / $perPage) : 1;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
if ($page < 1) $page = 1;
if ($page > $totalPages) $page = $totalPages;
$start = ($page - 1) * $perPage;
$automobili_paginated = array_slice($automobili, $start, $perPage);

// helper to build query string preserving other GET params
function build_query($overrides = []) {
    $params = $_GET;
    foreach ($overrides as $k => $v) {
        if ($v === null) {
            unset($params[$k]);
        } else {
            $params[$k] = $v;
        }
    }
    return http_build_query($params);
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Polovni automobili</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container-fluid p-5 bg-primary text-white text-center" style="padding: 5px !important;">
  <h3>Polovni automobili</h3>
</div>
  <br />

<div class="container">
    <form action="" method="GET">
  <div class="row">
        <div class="col-sm-3">
            <label  class="form-label">Model:</label>
            <input type="text" name="search_model" value="<?php echo htmlspecialchars($model_pretraga) ?>" />
        </div>
        <div class="col-sm-3">
            <label for="pwd" class="form-label">Proizvodjac:</label>
            <div class="dropdown">
                <button class="btn btn-outline-secondary dropdown-toggle w-100 text-start" type="button" id="dropdownProizvodjacBtn" data-bs-toggle="dropdown" aria-expanded="false">
                    Izaberi proizvodjace
                </button>
                <div class="dropdown-menu p-3" aria-labelledby="dropdownProizvodjacBtn" style="max-height:220px; overflow:auto; min-width:260px;">
                    <?php foreach($prozvodjaci as $proizvodjac){
                        $id = (string)$proizvodjac['id'];
                        $checked = in_array($id, $proizvodjac_pretraga) ? 'checked' : '';
                        ?>
                        <div class="form-check">
                            <input class="form-check-input prov-checkbox" type="checkbox" value="<?php echo $id ?>" id="prov_<?php echo $id ?>" name="search_proizvodjac[]" <?php echo $checked ?> />
                            <label class="form-check-label" for="prov_<?php echo $id ?>"><?php echo $proizvodjac['proizvodjac'] ?></label>
                        </div>
                    <?php } ?>
                </div>
            </div>

        </div>
        <div class="col-sm-3">
            <label for="pwd" class="form-label">Tip karoserije:</label>
            <div class="dropdown">
                <button class="btn btn-outline-secondary dropdown-toggle w-100 text-start" type="button" id="dropdownTipBtn" data-bs-toggle="dropdown" aria-expanded="false">
                    Izaberi tipove
                </button>
                <div class="dropdown-menu p-3" aria-labelledby="dropdownTipBtn" style="max-height:220px; overflow:auto; min-width:220px;">
                    <?php foreach($karoserije as $karoserija){
                        $id = (string)$karoserija['id'];
                        $checked = in_array($id, $tip_pretraga) ? 'checked' : '';
                        ?>
                        <div class="form-check">
                            <input class="form-check-input tip-checkbox" type="checkbox" value="<?php echo $id ?>" id="tip_<?php echo $id ?>" name="search_tip[]" <?php echo $checked ?> />
                            <label class="form-check-label" for="tip_<?php echo $id ?>"><?php echo $karoserija['karoserija'] ?></label>
                        </div>
                    <?php } ?>
                </div>
            </div>

        </div>
    </div>   
    <div class="row">
        <div class="col-sm-3">
            <label class="form-label">cena do:</label>
            <input type="number"  name="search_cena_do" value="<?php echo ($cena_do_pretraga != 0) ? htmlspecialchars($cena_do_pretraga) : '' ?>">
        </div>
        <div class="col-sm-3">
            <label class="form-label">godina od:</label>
            <input type="number"  name="search_godina_od" value="<?php echo ($godina_od_pretraga != 0) ? htmlspecialchars($godina_od_pretraga) : '' ?>">
        </div>
        
        <div class="col-sm-3">
            <label class="form-label">Sortiranje cene</label>
            <select name="sort">
                <option value="">Bez sortianja</option>
                <option value="rastuce" <?php echo (isset($_GET['sort']) && $_GET['sort'] == 'rastuce') ? 'selected' : '' ?>>cena rastuce</option>
                <option value="opadajuce" <?php echo (isset($_GET['sort']) && $_GET['sort'] == 'opadajuce') ? 'selected' : '' ?>>cena opadajuce</option>
            </select>

        </div>
        
        
        <div class="col-sm-3">
            <button type="submit" class="btn btn-primary">Pretraga</button>
        </div>
    </div>
</form>
</div>



<div class="container mt-3">
  <h2 id="spisak">Spisak automobila  </h2>
    <p id="brojac" style="text-align: right;">prikazano: <?php echo count($automobili_paginated) ?> od ukupno <?php echo $totalItems ?> automobila</p>
  <?php
    if ($postoji_pretraga) {
        ?>
            <p id="pamerametri_pretrage">Parametri pretrage: </p>
            <ul>
        <?php 
        if (isset($_GET['search_model']) && $_GET['search_model'] != ""  ) {
            echo "<li><span class='font-weight-bold'>Pretraga modela: </span> ".$_GET['search_model'];
        }
        if (!empty($_GET['search_proizvodjac'])) {
            // map ids to names
            $sel = (array) $_GET['search_proizvodjac'];
            $names = array();
            foreach($prozvodjaci as $p) {
                if (in_array((string)$p['id'], $sel)) $names[] = $p['proizvodjac'];
            }
            if (count($names) > 0) echo "<li><span class='font-weight-bold'>Pretraga proizvodjaca: </span> " . implode(', ', $names);
        }
        if (!empty($_GET['search_tip'])) {
            $sel = (array) $_GET['search_tip'];
            $names = array();
            foreach($karoserije as $k) {
                if (in_array((string)$k['id'], $sel)) $names[] = $k['karoserija'];
            }
            if (count($names) > 0) echo "<li><span class='font-weight-bold'>Pretraga karoserije: </span> " . implode(', ', $names);
        }
        if (isset($_GET['search_cena_do'])&& $_GET['search_cena_do'] != "" ) {
            echo "<li><span class='font-weight-bold'>Filter cene: </span> ".$_GET['search_cena_do'];
        }
        if (isset($_GET['search_godina_od']) && $_GET['search_godina_od'] != "" ) {
            echo "<li><span class='font-weight-bold'>Filter godina: </span> ".$_GET['search_godina_od'];
        }
        ?></ul>
        <form id="obrisi-pretragu" action="" method="GET">
            <button type="submit" class="btn btn-primary">Ponisti pretragu</button>
        </form>
        <?php
    }
  ?>           
  <table id="svi_automobili" class="table table-striped">
    <thead>
      <tr>
        <th>Slika</th>
        <th>Proizvodjac</th>
        <th>Model</th>
        <th>Godiste</th>
        <th>Cena</th>
        <!-- <th>Detalji</th> -->
      </tr>
    </thead>
    <tbody>
        <?php 
            foreach($automobili_paginated as $auto){
                ?>
                      <tr>
                        <td><a href="automobil.php?id=<?php echo $auto['automobil_id'] ?>"  ><img src="<?php echo $auto['slika'] ?>" alt="" width="100px" /></a></td>
                        <td><?php echo $auto['proizvodjac'] ?></td>
                        <td><?php echo $auto['model'] ?></td>
                        <td><?php echo $auto['godina_proizvodnje'] ?></td>
                        <td><?php echo $auto['cena'] ?></td>
                    </tr>
                <?php
            }
        
        ?>
    </tbody>
  </table>
  <div class="d-flex justify-content-between">
    <div>
        <form action="" method="GET">
            <?php // preserve other GET params but reset page to 1 when clearing search ?>
            <?php foreach($_GET as $k => $v) { if ($k !== 'page') { 
                    if (is_array($v)) {
                        foreach($v as $item) { ?>
                            <input type="hidden" name="<?php echo htmlspecialchars($k) ?>[]" value="<?php echo htmlspecialchars($item) ?>" />
                        <?php }
                    } else { ?>
                        <input type="hidden" name="<?php echo htmlspecialchars($k) ?>" value="<?php echo htmlspecialchars($v) ?>" />
                    <?php }
                } } ?>
            <button type="submit" class="btn btn-secondary" name="page" value="<?php echo max(1, $page - 1) ?>" <?php echo ($page <= 1) ? 'disabled' : '' ?>>&laquo; Prethodna</button>
        </form>
    </div>
    <div class="align-self-center">Strana <?php echo $page ?> od <?php echo $totalPages ?></div>
    <div>
        <form action="" method="GET">
            <?php foreach($_GET as $k => $v) { if ($k !== 'page') { 
                    if (is_array($v)) {
                        foreach($v as $item) { ?>
                            <input type="hidden" name="<?php echo htmlspecialchars($k) ?>[]" value="<?php echo htmlspecialchars($item) ?>" />
                        <?php }
                    } else { ?>
                        <input type="hidden" name="<?php echo htmlspecialchars($k) ?>" value="<?php echo htmlspecialchars($v) ?>" />
                    <?php }
                } } ?>
            <button type="submit" class="btn btn-secondary" name="page" value="<?php echo min($totalPages, $page + 1) ?>" <?php echo ($page >= $totalPages) ? 'disabled' : '' ?>>Sledeca &raquo;</button>
        </form>
    </div>
  </div>
  <a href="index.php?logout">LOG OUT</a>
</div>

<script>
// update dropdown button labels based on selections
function updateDropdownLabel(buttonId, selector, defaultLabel) {
    var checked = Array.from(document.querySelectorAll(selector)).filter(function(c){ return c.checked; });
    var btn = document.getElementById(buttonId);
    if (!btn) return;
    if (checked.length === 0) {
        btn.textContent = defaultLabel;
    } else if (checked.length === 1) {
        var label = checked[0].nextElementSibling ? checked[0].nextElementSibling.textContent.trim() : checked[0].value;
        btn.textContent = label;
    } else {
        btn.textContent = checked.length + ' izabrano';
    }
}

document.addEventListener('DOMContentLoaded', function(){
    // initialize labels
    updateDropdownLabel('dropdownProizvodjacBtn', '.prov-checkbox', 'Izaberi proizvodjace');
    updateDropdownLabel('dropdownTipBtn', '.tip-checkbox', 'Izaberi tipove');

    // attach change handlers
    document.querySelectorAll('.prov-checkbox').forEach(function(cb){
        cb.addEventListener('change', function(){ updateDropdownLabel('dropdownProizvodjacBtn', '.prov-checkbox', 'Izaberi proizvodjace'); });
    });
    document.querySelectorAll('.tip-checkbox').forEach(function(cb){
        cb.addEventListener('change', function(){ updateDropdownLabel('dropdownTipBtn', '.tip-checkbox', 'Izaberi tipove'); });
    });
});
</script>
</body>
</html>
