<?php
require_once __DIR__ . '/../includes/site_config.php';
site_start_session();

/* ADMIN */
$admin_user = site_env('TULCEA_SHOP_ADMIN', 'admin');
site_security_headers(true);
$csrf = site_csrf_token('shop_csrf');

/* DATA */
$file = "data.json";
if(!file_exists($file)) file_put_contents($file,"[]");
$products = json_decode((string)file_get_contents($file),true);
if (!is_array($products)) $products = [];

/* CART doar pentru clienti */
if(!isset($_SESSION['cart'])) $_SESSION['cart']=[];

/* LOGIN */
if(isset($_POST['login'])){
    $shopLoginAllowed = site_csrf_valid($_POST['csrf'] ?? null, 'shop_csrf')
        && site_rate_limit('shop_login', 6, 600);
    $shopLoginValid = $shopLoginAllowed
        && hash_equals($admin_user, (string)($_POST['user'] ?? ''))
        && site_secret_matches((string)($_POST['pass'] ?? ''), 'TULCEA_SHOP_PASSWORD');
    if($shopLoginValid){
        session_regenerate_id(true);
        site_rate_limit_clear('shop_login');
        $_SESSION['shop_admin']=true;
        $_SESSION['cart']=[]; // stergem cos cand devine admin
    } elseif ($shopLoginAllowed) {
        usleep(350000);
    }
}

/* LOGOUT */
if(isset($_GET['logout']) && site_csrf_valid($_GET['csrf'] ?? null, 'shop_csrf')){
    session_destroy();
    header("Location: index.php");
    exit;
}

/* UPLOAD */
function upload($f){
    if(!isset($f) || $f['error']!=0) return "";
    if(($f['size'] ?? 0) < 1 || $f['size'] > 5 * 1024 * 1024) return "";
    $mime=(new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);
    $extensions=['image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp','image/gif'=>'gif'];
    if(!isset($extensions[$mime]) || @getimagesize($f['tmp_name'])===false) return "";
    $dir="uploads/";
    if(!is_dir($dir)) mkdir($dir,0775,true);

    $name=bin2hex(random_bytes(12)).".".$extensions[$mime];
    $path=$dir.$name;

    if(move_uploaded_file($f['tmp_name'],$path)) return $path;
    return "";
}

/* ADD PRODUCT */
if(isset($_POST['add']) && isset($_SESSION['shop_admin']) && site_csrf_valid($_POST['csrf'] ?? null, 'shop_csrf')){
    $img=upload($_FILES['image']);
    if($img=="") die("UPLOAD ESUAT");

    $products[]=[
        "id"=>"PRD".time(),
        "name"=>trim((string)($_POST['name'] ?? '')),
        "price"=>max(0, (float)($_POST['price'] ?? 0)),
        "image"=>$img
    ];

    file_put_contents($file,json_encode($products, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    header("Location: index.php");
    exit;
}

/* DELETE */
if(isset($_GET['delete']) && isset($_SESSION['shop_admin']) && site_csrf_valid($_GET['csrf'] ?? null, 'shop_csrf')){
    $id=$_GET['delete'];

    $products=array_filter($products,function($p)use($id){
        return $p['id']!=$id;
    });

    file_put_contents($file,json_encode(array_values($products), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    header("Location: index.php");
    exit;
}

/* EDIT */
if(isset($_POST['saveedit']) && isset($_SESSION['shop_admin']) && site_csrf_valid($_POST['csrf'] ?? null, 'shop_csrf')){
    foreach($products as &$p){
        if($p['id']==$_POST['id']){
            $p['name']=site_text((string)($_POST['name'] ?? ''), 120);
            $p['price']=max(0, (float)($_POST['price'] ?? 0));
        }
    }
    unset($p);
    file_put_contents($file,json_encode($products, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    header("Location: index.php");
    exit;
}

/* ADD TO CART (DOAR CLIENTI) */
if(isset($_GET['addcart']) && !isset($_SESSION['shop_admin']) && site_csrf_valid($_GET['csrf'] ?? null, 'shop_csrf')){
    foreach($products as $p){
        if($p['id']==$_GET['addcart']){
            $_SESSION['cart'][]=$p;
        }
    }
    header("Location: index.php");
    exit;
}

/* CLEAR CART (DOAR CLIENTI) */
if(isset($_GET['clearcart']) && !isset($_SESSION['shop_admin']) && site_csrf_valid($_GET['csrf'] ?? null, 'shop_csrf')){
    $_SESSION['cart']=[];
    header("Location: index.php");
    exit;
}

/* TOTAL */
$total=0;
foreach($_SESSION['cart'] as $c){
    $total+=$c['price'];
}

/* WHATSAPP MESSAGE */
$msg="COMANDA:\n";
foreach($_SESSION['cart'] as $c){
    $msg.=$c['name']." - ".$c['price']." RON - COD: ".$c['id']."\n";
}
$msg.="TOTAL: ".$total." RON";
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>Magazin Online</title>

<style>
*{box-sizing:border-box}
body{margin:0;font-family:Arial,Helvetica,sans-serif;background:linear-gradient(135deg,#08111f,#0f1d33,#12465c);background-attachment:fixed;color:#eef;padding:20px}
.admin-fixed{position:fixed;top:12px;right:12px;z-index:9999;background:rgba(18,25,39,.9);color:#fff;border:1px solid #35d6ff;border-radius:30px;padding:10px 16px;text-decoration:none}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;max-width:1400px;margin:20px auto}
.card{background:rgba(17,25,40,.85);backdrop-filter:blur(12px);border:1px solid rgba(53,214,255,.18);border-radius:18px;padding:16px;box-shadow:0 18px 35px rgba(0,0,0,.35);transition:.25s;animation:fade .6s}
.card:hover{transform:translateY(-5px)}
@keyframes fade{from{opacity:0;transform:translateY(15px)}to{opacity:1;transform:none}}
.card img{width:100%;height:230px;object-fit:contain;border-radius:12px;background:#fff;padding:10px}
h4{font-size:16px;min-height:42px;color:#fff}
.price{font-size:22px;color:#52f58b;font-weight:bold}
.code{font-size:12px;color:#9fb2c8}
.btn{display:block;text-align:center;margin-top:10px;padding:12px;border-radius:999px;text-decoration:none;font-weight:bold;transition:.2s}
.btn:hover{transform:translateY(-2px)}
.cartbtn{background:linear-gradient(90deg,#00a7ff,#006cff);color:#fff}
.edit{background:linear-gradient(90deg,#ffb000,#ff7a00);color:#fff}
.del{background:linear-gradient(90deg,#ff4d4d,#d40000);color:#fff}
.wa{background:linear-gradient(90deg,#25D366,#0b9f4b);color:#fff}
.clear{background:#222;color:#fff}
.cartbox{position:fixed;right:12px;bottom:12px;width:240px;max-height:340px;overflow:auto;background:rgba(17,25,40,.88);backdrop-filter:blur(10px);border-radius:16px;padding:15px;border:1px solid rgba(53,214,255,.18);box-shadow:0 15px 30px rgba(0,0,0,.35);z-index:999}
.exit-shop{position:fixed;left:50%;transform:translateX(-50%);bottom:15px;background:linear-gradient(90deg,#00a7ff,#006cff);color:#fff;padding:12px 26px;border-radius:999px;text-decoration:none;font-weight:bold}
#login{border-radius:18px;box-shadow:0 20px 40px rgba(0,0,0,.45)}
#login input,#login button,form input,form button{padding:10px;border-radius:10px;border:1px solid #ccc;margin:5px}
@media(max-width:768px){
body{padding:10px}
.grid{grid-template-columns:1fr;gap:15px}
.card img{height:200px}
.cartbox{position:static;width:100%;max-height:none;margin:20px auto}
.admin-fixed{padding:9px 14px}
.exit-shop{left:10px;right:10px;transform:none;text-align:center}
}
</style>
<style id="shop-responsive-redesign">
:root{--shop-line:rgba(113,220,232,.2);--shop-panel:rgba(11,30,45,.9);--shop-cyan:#55dce6}
body{min-height:100vh;padding:clamp(10px,2vw,22px);padding-bottom:78px;background:radial-gradient(circle at 10% 5%,rgba(36,175,197,.18),transparent 30rem),linear-gradient(145deg,#071521,#0a2738 55%,#071b2b);font-size:14px}
.grid{grid-template-columns:repeat(auto-fit,minmax(min(100%,190px),1fr));gap:12px;width:min(1120px,calc(100% - 250px));max-width:none;margin:12px auto 20px 0}
.card{min-width:0;padding:11px;border-radius:14px;box-shadow:0 12px 27px rgba(0,0,0,.28)}
.card:hover{transform:translateY(-3px);border-color:rgba(85,220,230,.38)}
.card img{height:150px;padding:6px;border-radius:9px}
h4{min-height:34px;margin:10px 0 7px;font-size:14px;line-height:1.25}
.price{font-size:18px}.code{font-size:10px}.btn{margin-top:7px;padding:8px 10px;font-size:12px}
.admin-fixed{top:10px;right:10px;padding:8px 13px;border-radius:12px;font-size:12px}
#login.login-modal{position:fixed!important;top:50%!important;left:50%!important;width:min(360px,calc(100vw - 24px));padding:18px!important;border:1px solid var(--shop-line);border-radius:16px!important;background:rgba(245,251,255,.98)!important;transform:translate(-50%,-50%);z-index:99999!important}
#login form{display:grid;gap:8px}#login input,#login button{width:100%;margin:0}
.admin-add,.edit-panel{width:min(720px,100%);margin:12px auto!important;padding:14px!important;border:1px solid var(--shop-line)!important;border-radius:15px!important;background:var(--shop-panel)!important;box-shadow:0 14px 30px rgba(0,0,0,.25)}
.admin-add{display:flex;flex-wrap:wrap;gap:7px}.admin-add input,.admin-add button,.edit-panel input,.edit-panel button{min-width:0;margin:0;flex:1 1 150px}
.edit-panel form{display:flex;flex-wrap:wrap;gap:7px}.edit-panel input,.edit-panel button{margin:0}
.cartbox{right:12px;bottom:68px;width:220px;max-height:calc(100vh - 110px);padding:12px;border-radius:14px;font-size:12px}.cartbox h4{min-height:0;margin-top:0}.cartbox .btn{padding:8px}
.exit-shop{bottom:12px;padding:9px 20px;font-size:12px;box-shadow:0 10px 25px rgba(0,32,90,.35)}
@media(max-width:980px){.grid{width:calc(100% - 220px);grid-template-columns:repeat(auto-fit,minmax(min(100%,170px),1fr))}.cartbox{width:200px}}
@media(max-width:760px){html{-webkit-text-size-adjust:100%}body{padding:8px 8px 72px}.grid{width:100%;max-width:540px;grid-template-columns:1fr;gap:10px;margin:10px auto}.card{width:100%;padding:10px;border-radius:14px}.card img{display:block;width:100%;height:auto;max-height:none;aspect-ratio:4/3;object-fit:contain;padding:6px}.card h4{min-height:0;margin:10px 0 7px;font-size:clamp(15px,4.2vw,18px);line-height:1.25}.price{font-size:clamp(18px,5vw,22px)}.code{font-size:11px}.card .btn{min-height:44px;display:flex;align-items:center;justify-content:center;padding:9px 12px;font-size:clamp(13px,3.8vw,15px)}.cartbox{position:static;width:100%;max-width:540px;max-height:none;margin:12px auto;padding:12px;font-size:14px}.cartbox .btn{min-height:43px;font-size:13px}.exit-shop{left:8px;right:8px;bottom:8px;min-height:43px;display:flex;align-items:center;justify-content:center;padding:8px;transform:none;font-size:14px}.admin-add,.edit-panel{padding:10px!important}.admin-fixed{font-size:12px}}
@media(max-width:430px){.grid{max-width:100%}.card{padding:8px}.card img{aspect-ratio:1/1}.price{font-size:19px}.admin-add,.edit-panel,.admin-add input,.admin-add button,.edit-panel input,.edit-panel button{width:100%}}
@media(max-width:900px) and (max-height:500px) and (orientation:landscape){body{padding-bottom:58px}.grid{max-width:100%;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.card img{height:150px;aspect-ratio:auto}.card h4{font-size:13px}.card .btn{min-height:38px;font-size:12px}.exit-shop{min-height:38px}}
@media(prefers-reduced-motion:reduce){.card{animation:none;transition:none}}
</style>
</head>

<body>

<!-- ADMIN BUTTON -->
<?php if(!isset($_SESSION['shop_admin'])): ?>
<button class="admin-fixed" onclick="document.getElementById('login').style.display='block'">Admin</button>
<?php else: ?>
<a class="admin-fixed" href="?logout=1&amp;csrf=<?=urlencode($csrf)?>">Logout</a>
<?php endif; ?>

<!-- LOGIN -->
<div id="login" class="login-modal" style="display:none;position:fixed;top:40%;left:40%;background:#fff;padding:20px;z-index:99999">
<form method="post">
<input type="hidden" name="csrf" value="<?=htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8')?>">
<input name="user" placeholder="user">
<input name="pass" type="password" placeholder="pass">
<button name="login">Login</button>
</form>
</div>

<!-- ADD PRODUCT (ADMIN) -->
<?php if(isset($_SESSION['shop_admin'])): ?>
<form class="admin-add" method="post" enctype="multipart/form-data" style="padding:20px">
<input type="hidden" name="csrf" value="<?=htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8')?>">
<input name="name" placeholder="Nume produs">
<input name="price" placeholder="Pret">
<input type="file" name="image">
<button name="add">Adauga</button>
</form>
<?php endif; ?>

<!-- EDIT -->
<?php if(isset($_GET['edit']) && isset($_SESSION['shop_admin'])): 
$eid=$_GET['edit'];
$ep=null;
foreach($products as $p){
    if($p['id']==$eid) $ep=$p;
}
?>
<div class="edit-panel" style="background:#fff;padding:20px;margin:20px;border-radius:10px;">
<form method="post">
<input type="hidden" name="csrf" value="<?=htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8')?>">
<input type="hidden" name="id" value="<?=htmlspecialchars((string)($ep['id'] ?? ''), ENT_QUOTES, 'UTF-8')?>">
<input name="name" value="<?=htmlspecialchars((string)($ep['name'] ?? ''), ENT_QUOTES, 'UTF-8')?>">
<input name="price" value="<?=htmlspecialchars((string)($ep['price'] ?? ''), ENT_QUOTES, 'UTF-8')?>">
<button name="saveedit">Salveaza</button>
</form>
</div>
<?php endif; ?>

<!-- PRODUCTS -->
<div class="grid">

<?php foreach($products as $p): ?>
<div class="card">

<img src="<?=htmlspecialchars((string)$p['image'], ENT_QUOTES, 'UTF-8')?>" alt="">

<h4><?=htmlspecialchars((string)$p['name'], ENT_QUOTES, 'UTF-8')?></h4>

<div class="price"><?=htmlspecialchars((string)$p['price'], ENT_QUOTES, 'UTF-8')?> RON</div>

<div class="code">Cod: <?=htmlspecialchars((string)$p['id'], ENT_QUOTES, 'UTF-8')?></div>

<!-- CLIENT ONLY -->
<?php if(!isset($_SESSION['shop_admin'])): ?>
<a class="btn cartbtn" href="?addcart=<?=urlencode((string)$p['id'])?>&amp;csrf=<?=urlencode($csrf)?>">Adauga in cos</a>
<?php endif; ?>

<!-- ADMIN ONLY -->
<?php if(isset($_SESSION['shop_admin'])): ?>
<a class="btn edit" href="?edit=<?=urlencode((string)$p['id'])?>">Edit</a>
<a class="btn del" href="?delete=<?=urlencode((string)$p['id'])?>&amp;csrf=<?=urlencode($csrf)?>">Delete</a>
<?php endif; ?>

</div>
<?php endforeach; ?>

</div>

<!-- CART DOAR CLIENT -->
<?php if(!isset($_SESSION['shop_admin'])): ?>
<div class="cartbox">

<h4>Cos</h4>

<?php foreach($_SESSION['cart'] as $c): ?>
<div><?=htmlspecialchars((string)$c['name'], ENT_QUOTES, 'UTF-8')?> - <?=htmlspecialchars((string)$c['price'], ENT_QUOTES, 'UTF-8')?> RON</div>
<?php endforeach; ?>

<hr>

<?php $total=0; foreach($_SESSION['cart'] as $c){ $total+=$c['price']; } ?>

<b>Total: <?=$total?> RON</b>

<br><br>

<a class="btn wa" target="_blank"
href="https://wa.me/40723117520?text=<?=urlencode($msg)?>">
Trimite pe WhatsApp
</a>

<a class="btn clear" href="?clearcart=1&amp;csrf=<?=urlencode($csrf)?>">Goleste cos</a>

</div>
<?php endif; ?>

<!-- EXIT SHOP BUTTON -->
<a href="https://tulcea.home.ro" class="exit-shop">Exit Shop</a>

<script>
document.addEventListener('contextmenu', event => event.preventDefault());
</script>
<!-- ROBOT TULCEA.HOME.RO - MIJLOC DREAPTA -->

<link rel="stylesheet" href="/robot/robot.css?v=20260823-GLOBAL-1">

<style>
#tulcea-robot-root .tr-launcher {
    position: fixed !important;
    top: 50% !important;
    right: 15px !important;
    bottom: auto !important;
    left: auto !important;
    transform: translateY(-50%) !important;
    z-index: 999999 !important;
}

#tulcea-robot-root .tr-panel {
    position: fixed !important;
    top: 50% !important;
    right: 125px !important;
    bottom: auto !important;
    left: auto !important;
    transform: translateY(-50%) !important;
    z-index: 999999 !important;
}

#tulcea-robot-root .tr-bubble {
    position: fixed !important;
    top: 50% !important;
    right: 125px !important;
    bottom: auto !important;
    left: auto !important;
    transform: translateY(-50%) !important;
    z-index: 999999 !important;
}
</style>

<script>
(function () {
    function incarcaRobotTulcea() {

        if (window.TulceaRobotLoaded) {
            return;
        }

        if (document.querySelector('script[data-tulcea-robot-global]')) {
            return;
        }

        var script = document.createElement("script");
        script.src = "/robot/robot.js?v=20260823-GLOBAL-1";
        script.async = false;
        script.setAttribute("data-tulcea-robot-global", "1");

        document.body.appendChild(script);
    }

    if (document.readyState === "loading") {
        document.addEventListener(
            "DOMContentLoaded",
            incarcaRobotTulcea,
            { once: true }
        );
    } else {
        incarcaRobotTulcea();
    }
})();
</script>

<!-- SFARSIT ROBOT TULCEA.HOME.RO -->

</body>
</html>
