<?php
require_once "../../includes/islogin.php";
require '../../includes/db_connect.php';

// DB 연결
$host = "infodb.ansan.ac.kr";
$user = "i2151040";
$password = "qkaqka0019@";
$dbname = "db2151040_capstone";

$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("연결 실패: " . $conn->connect_error);
}

// 좌석 예약 처리
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['seat_number'])) {
        $seatNumber = $_POST['seat_number'];
        $reservedBy = $_POST['reserved_by'];

        $stmt = $conn->prepare("INSERT INTO Table_reservations (seat_number, reserved_by) VALUES (?, ?)");
        $stmt->bind_param("ii", $seatNumber, $reservedBy);
        $stmt->execute();
        $stmt->close();
        header("Location: table-seat-reserve.php");
        exit;
    }

    if (isset($_POST['cancel_seat_number'])) {
        $stmt = $conn->prepare("DELETE FROM Table_reservations WHERE seat_number = ? AND reserved_by = ?");
        $stmt->bind_param("ii", $_POST['cancel_seat_number'], $_POST['reserved_by']);
        $stmt->execute();
        $stmt->close();
        header("Location: table-seat-reserve.php");
        exit;
    }
}

// 좌석 현황 조회
function getReservedSeats($conn) {
    $reservedSeats = [];
    $query = "SELECT seat_number FROM Table_reservations";
    $result = $conn->query($query);
    while ($row = $result->fetch_assoc()) {
        $reservedSeats[$row['seat_number']] = true;
    }
    return $reservedSeats;
}

// 세션 시작
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$user_id = $_SESSION['user_id'] ?? 0;
$reserved = getReservedSeats($conn);
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>좌석 예매</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
        }

        .container {
            height: 100%;
            display: flex;
            flex-direction: column;
            max-width: 400px;
            margin: 0 auto;
        }

        .app-container {
            max-width: 500px;
            height: 100%;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        .main-content {
            flex: 1;
            overflow-y: auto;
        }
        .back-button {
            text-decoration: none;
            color: #555;
            font-size: 1.5em;
            display: flex;
            align-items: center;
            padding: 5px 10px;
            cursor: pointer;
            border-radius: 50%;
            transition: background 0.2s;
        }
        .header .back-button:hover {
            background: #f0f0f0;
        }
        .seat-grid {
            display: grid;
            grid-template-columns: repeat(10, 1fr);
            gap: 10px;
            margin-top: 20px;
        }
        .seat {
            width: 32px;
            height: 32px;
            margin: 4px;
            background-color: #fff;
            border: 1px solid #888;
            border-radius: 4px;
            display: inline-block;
            line-height: 32px;
            font-size: 13px;
            text-align: center;
            cursor: pointer;
        }
        .seat.reserved {
            background-color: #aaa;
            color: white;
            cursor: not-allowed;
        }
        .seat.selected {
            background-color: #4caf50;
            color: white;
        }
        .actions {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        .actions button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 48%;
        }
        .actions button:hover {
            background-color: #0056b3;
        }
        .seat-image {
            width: 100%;
            max-width: 100%;
            margin-bottom: 15px;
        }
        .seat-image img {
            width: 500px;
            height: 250px;
            object-fit: contain;
            display: block;
            margin: 0 auto;
        }
        nav.bottom-nav {
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 10px 0;
            border-top: 1px solid #eee;
            background-color: white;
            flex-shrink: 0;
        }

        .bottom-nav a {
            color: #555;
            font-size: 1.5em;
            text-decoration: none;
            padding: 5px 10px;
            transition: color 0.2s;
        }

        .bottom-nav a:hover,
        .bottom-nav a.active {
            color: #007bff;
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
<div class="app-container">
  <div class="main-content">
    <div class="header">
      <a href="javascript:history.back();" class="back-button"><i class="fas fa-arrow-left"></i></a>
    </div>
    <h2>좌석 예매</h2>

    <div class="seat-image">
        <img src="../assets/images/seat.png" alt="좌석 이미지">
    </div>

    <div class="seat-grid" id="seatGrid"></div>

    <form method="POST" id="reserveForm">
        <input type="hidden" name="reserved_by" value="<?= htmlspecialchars($user_id) ?>">
        <input type="hidden" name="seat_number" id="seatNumberInput">
        <div class="actions">
            <button type="submit">예매하기</button>
            <button type="button" id="cancelButton">예매 취소</button>
        </div>
    </form>

<script>
    const reservedSeats = <?php echo json_encode($reserved); ?>;
    const seatGrid = document.getElementById('seatGrid');
    let selectedSeat = null;

    const seatNumbers = [
        1, 6, 11, 16, 21, 26, 31, 36, 41, 46,
        2, 7, 12, 17, 22, 27, 32, 37, 42, 47,
        3, 8, 13, 18, 23, 28, 33, 38, 43, 48,
        4, 9, 14, 19, 24, 29, 34, 39, 44, 49,
        5, 10, 15, 20, 25, 30, 35, 40, 45, 50
    ];

    seatNumbers.forEach(seat => {
        const btn = document.createElement('div');
        btn.className = 'seat';
        btn.textContent = seat;

        if (reservedSeats[seat.toString()]) {
            btn.classList.add('reserved');
        }

        btn.addEventListener('click', () => {
            if (btn.classList.contains('reserved')) return;

            if (selectedSeat) {
                selectedSeat.classList.remove('selected');
            }

            selectedSeat = btn;
            selectedSeat.classList.add('selected');
            document.getElementById('seatNumberInput').value = selectedSeat.textContent;
        });

        seatGrid.appendChild(btn);
    });

    // 예매 취소 버튼 클릭 시
    document.getElementById('cancelButton').addEventListener('click', () => {
        if (selectedSeat) {
            // 선택된 좌석에서 'selected' 클래스를 제거
            selectedSeat.classList.remove('selected');
            
            // 좌석 번호 입력 필드 초기화
            document.getElementById('seatNumberInput').value = '';
            
            // 선택된 좌석 변수 초기화
            selectedSeat = null;
        } else {
            alert("선택된 좌석이 없습니다.");
        }
    });
</script>

<nav class="bottom-nav">
    <a href="../../main.html" class="active"><i class="fas fa-home"></i></a>
    <a href="../user/dibs.php"><i class="fas fa-heart"></i></a>
    <a href="../oreder/orderlist.php"><i class="fas fa-receipt"></i></a>
    <a href="../../auth/redirect-mypage.php"><i class="fas fa-user"></i></a>
</nav>

  </div>
</div>
</body>
</html>
