<?php 
// Versión simplificada para revendedores - manteniendo lógica original
include(__DIR__ . '/includes/functions.php');
include(__DIR__ . '/includes/json_utils.php');

$selected_uid = isset($_GET['uuid']) ? $_GET['uuid'] : '';
$get_macaddress = isset($_GET['mac']) ? $_GET['mac'] : '';

/////////current page/////////
$currunt_page = isset($_GET['view']) ? $_GET['view'] : '';
$selected_page;

if($currunt_page > 0){
    $selected_page = "&view=".$currunt_page;
}else{
    $selected_page = '';
}
/////////current page/////////	
//table name
$table_name = "ibof";
$table_name_advance = "devop";
$table_name_sort = 'sort';
$table_name_dns = "dns";
$page_user = basename($_SERVER['PHP_SELF']); // Usar el mismo archivo
$pagemac = "mac_manage.php";

//dns call
$resdns = $db->select($table_name_dns, '*', '', '');

//advance option db
$advance = $db->select($table_name_advance, '*', 'id = :id', '', [':id' => 1]);
$per_pagexx = !empty($advance[0]['maxpg']) ? $advance[0]['maxpg'] : '8';

//update call
@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);

//sort table
$ressort = $db->select($table_name_sort, '*', '', '');
$sortval = $ressort[0]['sort'] ? : 'def';

$data_sort = ['sort' => 'def'];
$db->insertIfEmpty($table_name_sort, $data_sort);

/////////////Search and page area////////////////////////////

$results_per_page = $per_pagexx;

if (isset($_GET['view'])) {
    $page = $_GET['view'];
} else {
    $page = 1;
}

$start_from = ($page - 1) * $results_per_page;

$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$placeholders = [];
$searchQuery = '';

if (!empty($searchTerm)) {
    $searchQuery = "macad LIKE :searchTerm OR name LIKE :searchTerm";
    $placeholders[':searchTerm'] = "%$searchTerm%";
}

// 2. Determine sort order (default A-Z)
$sortOrder = 'name ASC';
switch ($sortval) {
        case 'def':
            $sortOrder = 'name ASC';
            break;
        case 'AtoZ':
            $sortOrder = 'name ASC';
            break;
        case 'ZtoA':
            $sortOrder = 'name DESC';
            break;
        case 'Mark_F':
            $sortOrder = 'mark DESC';
            break;
        case 'UNMark_F':
            $sortOrder = 'mark ASC';
            break;
        case 'new_F':
            $sortOrder = 'cdate DESC';
            break;
        case 'old_F':
            $sortOrder = 'cdate ASC';
            break;
        case 'newu_F':
            $sortOrder = 'udate DESC';
            break;
        case 'oldu_F':
            $sortOrder = 'udate ASC';
            break;
}

// 3. Pagination calculation - SOLO si hay búsqueda
$totaleview = 0;
$total_pages = 0;
if (!empty($searchTerm)) {
    $countResult = $db->selectWithCount($table_name, "id", $searchQuery, $placeholders);
    $totaleview = $countResult[0]['total'];
    $total_pages = ceil($totaleview / $results_per_page);
}

// 4. Fetch records - SOLO si hay búsqueda específica
$res = [];
if (!empty($searchTerm)) {
    $res = $db->select(
        $table_name,
        '*',
        $searchQuery,
        "$sortOrder LIMIT $start_from, $results_per_page",
        $placeholders
    );
}

/////////////////////////////////////////////////////////////

if(isset($_POST['submitU'])){
    unset($_POST['submitU']);
    $updateData = $_POST;
    $db->update($table_name, $updateData, 'id = :id',[':id' => $_GET['update']]);
    echo "<script>window.location.href='".$page_user."?status=ok$selected_page'</script>";
}

//submit new
if (isset($_POST['submit'])){
    unset($_POST['submit']);
    $db->insert($table_name, $_POST);
    $db->close();
    echo "<script>window.location.href='".$page_user."?status=ok'</script>";
}

//sort save
if(isset($_POST['submitS'])){
    unset($_POST['submitS']);
    $updateData = $_POST;
    $db->update($table_name_sort, $updateData, 'id = :id',[':id' => 1]);
    echo "<script>window.location.href='".$page_user."?status=ok'</script>";
}

//delete row
if(isset($_GET['delete'])){
    $db->delete($table_name, 'id = :id',[':id' => $_GET['delete']]);
    echo "<script>window.location.href='".$page_user."?status=ok'</script>";
}

if(isset($_GET['mark'])){
    mark($_GET['mark'],$currunt_page);
}

function mark($idmy,$page){
    global $db;
    $table_name = "ibof";
    $page_user = basename($_SERVER['PHP_SELF']);
    $ret = $db->select($table_name, '*', 'id = :id', '', [':id' => $idmy]);
    
    $page_no;
    $newmark;
    $mark = $ret[0]['mark'];
    
    if($mark == 0){
        $newmark = 1;
    }else{
        $newmark = 0;
    }
    
    if($page > 0){
        $page_no = "&view=".$page;
    }
    else{
        $page_no = '';
    }
    
    $data = ['mark' => $newmark];
    $db->update($table_name, $data, 'id = :id',[':id' => $idmy]);
    echo "<script>window.location.href='".$page_user."?status=ok$page_no'</script>";
}

function getdnsname($uuidmy){
    global $db;
    $ret = $db->select('dns', '*', 'uid = :uid', '', [':uid' => $uuidmy]);
    $dnsname = $ret[0]['title'];
    $dnsurl = $ret[0]['url'];
    
    if($dnsname =='' || $dnsname == null){
        return 'DNS missing → '.$uuidmy;
    }else{
      return $dnsname .' → '. $dnsurl;  
    }
}

function getCurrentDateTimeAuto() {
    $timezone = @date_default_timezone_get();
    if (!$timezone) {
        $timezone = 'UTC';
    }
    date_default_timezone_set($timezone);
    return date('Y-m-d H:i:s');
}

function PlaylistID() {
    $timezone = @date_default_timezone_get();
    if (!$timezone) {
        $timezone = 'UTC';
    }
    date_default_timezone_set($timezone);
    $time = date('Y-m-d H:i:s');
    $mix = md5($time).$time;
    return hash('sha256', $mix);
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestión de Clientes IPTV</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
            background: linear-gradient(to right, #0f2027, #203a43, #2c5364);
            color: #f0f0f0;
            min-height: 100vh;
        }
        .main-card {
            max-width: 1200px;
            margin: auto;
            background: #1e1e2f;
            padding: 30px 25px;
            border-radius: 14px;
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
        }
        .card-header h3, .card-header h5 {
            color: white !important;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #5a6fd1 0%, #6a4299 100%);
        }
        .table th {
            background-color: #495057;
            color: white;
        }
        .table td {
            background-color: #2d2d3d;
            color: white;
        }
        .form-control, .form-select {
            background-color: #2d2d3d;
            border-color: #495057;
            color: white;
        }
        .form-control:focus, .form-select:focus {
            background-color: #2d2d3d;
            border-color: #667eea;
            color: white;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .form-control::placeholder {
            color: #adb5bd !important;
            opacity: 0.8;
        }
        .form-label {
            color: white !important;
            font-weight: 500;
            margin-bottom: 8px;
        }
        .bg-secondary {
            background-color: #1e1e2f !important;
        }
        .text-primary {
            color: #667eea !important;
        }
    </style>
</head>
<body>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var macAddressInput = document.getElementById("mac_address");
    if(macAddressInput) {
        macAddressInput.addEventListener("input", function(e) {
            var value = e.target.value;
            value = value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();

            var formattedValue = "";
            for (var i = 0; i < value.length; i++) {
                formattedValue += value[i];
                if ((i + 1) % 2 === 0 && i < value.length - 1) {
                    formattedValue += ":";
                }
            }
            e.target.value = formattedValue;
        });
    }
});
</script>

<?php if (isset($_GET['create'])){?>
<!-- Create Form -->
<div class="main-card">
    <div class="card-header text-center mb-4">
        <h3><i class="fas fa-tv"></i> Gestión de Clientes IPTV</h3>
        <h5>Agregar Nuevo Cliente</h5>
    </div>
    
    <form method="post">
        <div class="mb-3">
            <input type="hidden" name="plid" class="form-control" value="<?=PlaylistID(); ?>" readonly>
        </div>
        <div class="mb-3">
            <label class="form-label">Nombre del Playlist</label>
            <input type="text" name="name" class="form-control" placeholder="Ingrese el nombre del playlist" required>
        </div>
        <div class="mb-3">
            <label class="form-label">DNS</label>
            <select class="form-select" name="uuid">
                <?php foreach ($resdns as $title): ?>
                <option value="<?= htmlspecialchars($title['uid']); ?>" <?= $title['uid'] == $selected_uid ? 'selected' : ''; ?>>
                    <?= htmlspecialchars($title['title']); ?> → <?= htmlspecialchars($title['url']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label class="form-label">MAC Address</label>
            <input type="text" name="macad" id="mac_address" value="<?=$get_macaddress ?>" class="form-control" placeholder="Ejemplo: AA:BB:CC:DD:EE:FF" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Usuario</label>
            <input type="text" name="username" class="form-control" placeholder="Ingrese el nombre de usuario">
        </div>
        <div class="mb-3">
            <label class="form-label">Contraseña</label>
            <input type="text" name="password" class="form-control" placeholder="Ingrese la contraseña">
        </div>
        <div class="mb-3">
            <label class="form-label">Protegido</label>
            <select class="form-select" name="protec">
                <option value="1">Sí</option>
                <option value="0">No</option>
            </select>
        </div>
        <div class="mb-3">
            <input type="hidden" name="cdate" value="<?=getCurrentDateTimeAuto(); ?>">
            <input type="hidden" name="udate" value="<?=getCurrentDateTimeAuto(); ?>">
            <input type="hidden" name="mark" value="0">
        </div>
        <div class="d-flex gap-2">
            <button type="submit" name="submit" class="btn btn-success">
                <i class="fas fa-save"></i> Guardar Cliente
            </button>
            <a href="<?=$page_user?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
        </div>
    </form>
</div>

<?php } else if (isset($_GET['update'])){ ?>
<!-- Update Form -->
<div class="main-card">
    <div class="card-header text-center mb-4">
        <h3><i class="fas fa-tv"></i> Gestión de Clientes IPTV</h3>
        <h5>Editar Cliente</h5>
    </div>
    
    <form method="post">
        <div class="mb-3">
            <input type="hidden" name="plid" value="<?=$resU[0]['plid'] ?>">
        </div>
        <div class="mb-3">
            <label class="form-label">Nombre del Playlist</label>
            <input type="text" name="name" class="form-control" value="<?=$resU[0]['name'] ?>" placeholder="Ingrese el nombre del playlist" required>
        </div>
        <div class="mb-3">
            <label class="form-label">DNS</label>
            <select class="form-select" name="uuid">
                <?php foreach ($resdns as $title): ?>
                <option value="<?= htmlspecialchars($title['uid']); ?>" <?= $title['uid'] == $resU[0]['uuid'] ? 'selected' : ''; ?>>
                    <?= htmlspecialchars($title['title']); ?> → <?= htmlspecialchars($title['url']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label class="form-label">MAC Address</label>
            <input type="text" name="macad" id="mac_address" class="form-control" value="<?=$resU[0]['macad'] ?>" placeholder="Ejemplo: AA:BB:CC:DD:EE:FF" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Usuario</label>
            <input type="text" name="username" class="form-control" value="<?=$resU[0]['username'] ?>" placeholder="Ingrese el nombre de usuario">
        </div>
        <div class="mb-3">
            <label class="form-label">Contraseña</label>
            <input type="text" name="password" class="form-control" value="<?=$resU[0]['password'] ?>" placeholder="Ingrese la contraseña">
        </div>
        <div class="mb-3">
            <label class="form-label">Protegido</label>
            <select class="form-select" name="protec">
                <option value="1" <?=$resU[0]['protec']=='1'?'selected':'' ?>>Sí</option>
                <option value="0" <?=$resU[0]['protec']=='0'?'selected':'' ?>>No</option>
            </select>
        </div>
        <div class="mb-3">
            <input type="hidden" name="cdate" value="<?=$resU[0]['cdate'] ?>">
            <input type="hidden" name="udate" value="<?=getCurrentDateTimeAuto(); ?>">
            <input type="hidden" name="mark" value="<?=$resU[0]['mark'] ?>">
        </div>
        <div class="d-flex gap-2">
            <button type="submit" name="submitU" class="btn btn-success">
                <i class="fas fa-save"></i> Actualizar Cliente
            </button>
            <a href="<?=$page_user.$selected_page?>" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
        </div>
    </form>
</div>

<?php } else { ?>
<!-- Main Interface -->
<div class="main-card">
    <div class="card-header text-center mb-4">
        <h3><i class="fas fa-tv"></i> Gestión de Clientes IPTV</h3>
        <h5>Busca y gestiona las MAC addresses de tus clientes</h5>
        <a href="<?=$page_user?>?create" class="btn btn-success">
            <i class="fas fa-plus"></i> Agregar Cliente
        </a>
    </div>

    <!-- Search -->
    <div class="row mb-4">
        <div class="col-md-8">
            <form method="get" class="mb-0">
                <div class="input-group">
                    <input type="text" name="search" class="form-control" value="<?=$searchTerm?>" placeholder="Buscar por MAC Address o Nombre">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i> Buscar
                    </button>
                </div>
            </form>
        </div>
        <div class="col-md-4">
            <div class="dropdown">
                <button class="btn btn-outline-light dropdown-toggle w-100" type="button" data-bs-toggle="dropdown">
                    <i class="fas fa-sort"></i> Ordenar
                </button>
                <ul class="dropdown-menu bg-dark">
                    <li>
                        <form method="post" class="mb-0">
                            <input type="hidden" name="sort" value="def">
                            <button type="submit" name="submitS" class="dropdown-item text-light">Por Defecto</button>
                        </form>
                    </li>
                    <li>
                        <form method="post" class="mb-0">
                            <input type="hidden" name="sort" value="AtoZ">
                            <button type="submit" name="submitS" class="dropdown-item text-light">A a Z</button>
                        </form>
                    </li>
                    <li>
                        <form method="post" class="mb-0">
                            <input type="hidden" name="sort" value="ZtoA">
                            <button type="submit" name="submitS" class="dropdown-item text-light">Z a A</button>
                        </form>
                    </li>
                    <li>
                        <form method="post" class="mb-0">
                            <input type="hidden" name="sort" value="new_F">
                            <button type="submit" name="submitS" class="dropdown-item text-light">Más Recientes</button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </div>

    <!-- Results -->
    <?php if(!empty($searchTerm)): ?>
        <?php if($res): ?>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Nombre</th>
                        <th>MAC Address</th>
                        <th>DNS</th>
                        <th>Protegido</th>
                        <th>Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($res as $row) { ?>
                    <tr>
                        <td><?= htmlspecialchars($row['name']) ?></td>
                        <td><?= htmlspecialchars($row['macad']) ?></td>
                        <td><?= htmlspecialchars(getdnsname($row['uuid'])) ?></td>
                        <td>
                            <?= $row['protec'] == 1 ? '<span class="badge bg-warning">Sí</span>' : '<span class="badge bg-success">No</span>' ?>
                        </td>
                        <td>
                            <a href="<?=$page_user?>?update=<?=$row['id']?>&uuid=<?=$row['uuid']?><?=$selected_page?>" 
                               class="btn btn-sm btn-primary">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="<?=$page_user?>?delete=<?=$row['id']?><?=$selected_page?>" 
                               class="btn btn-sm btn-danger" 
                               onclick="return confirm('¿Está seguro de eliminar este cliente?')">
                                <i class="fas fa-trash"></i>
                            </a>
                            <a href="<?=$page_user?>?mark=<?=$row['id']?><?=$selected_page?>" 
                               class="btn btn-sm <?= $row['mark'] == 1 ? 'btn-warning' : 'btn-outline-warning' ?>">
                                <i class="fas fa-star"></i>
                            </a>
                        </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="<?=$page_user?>?view=<?=$page-1?>&search=<?=$searchTerm?>">Anterior</a>
                    </li>
                <?php endif; ?>
                
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="<?=$page_user?>?view=<?=$i?>&search=<?=$searchTerm?>"><?=$i?></a>
                    </li>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="<?=$page_user?>?view=<?=$page+1?>&search=<?=$searchTerm?>">Siguiente</a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>
        <?php endif; ?>
        
        <?php else: ?>
        <div class="alert alert-info text-center">
            <i class="fas fa-info-circle"></i> 
            No se encontraron resultados para: <?= htmlspecialchars($searchTerm) ?>
        </div>
        <?php endif; ?>
    <?php else: ?>
    <div class="alert alert-secondary text-center">
        <i class="fas fa-search"></i> 
        Ingrese una MAC address o nombre para buscar clientes
    </div>
    <?php endif; ?>
</div>

<?php } ?>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>