<?php
require_once('../../includes/db_connect.php');
require_once('../../includes/islogin.php');

$coupons_list = [];
$register_success_message = '';
$register_error_message = '';

// 현재 로그인한 사용자 ID 가져오기
if (!isset($_SESSION['user_id'])) {
    die("로그인이 필요합니다.");
}
$user_id = $_SESSION['user_id'];

// 쿠폰 코드 등록 폼 처리
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register_coupon_code_submit'])) {
    $entered_code_original = trim($_POST['coupon_code_input'] ?? '');
    $entered_code = strtoupper($entered_code_original);

    if (empty($entered_code)) {
        $register_error_message = "쿠폰 코드를 입력해주세요.";
    } else {
        if (isset($conn) && $conn instanceof mysqli && !$conn->connect_error) {
            // 1. 쿠폰 테이블에서 코드 확인
            $coupon_id = null;
            $coupon_valid_until = null;

            $stmt_check_coupon = $conn->prepare("SELECT coupon_id, valid_until FROM Coupons WHERE code = ?");
            $stmt_check_coupon->bind_param("s", $entered_code);
            $stmt_check_coupon->execute();
            $result_check_coupon = $stmt_check_coupon->get_result();

            if ($coupon_row = $result_check_coupon->fetch_assoc()) {
                $coupon_id = $coupon_row['coupon_id'];
                $coupon_valid_until = $coupon_row['valid_until'];

                // 2. 쿠폰 유효기간 확인
                if (strtotime($coupon_valid_until) < strtotime(date('Y-m-d'))) {
                    $register_error_message = "만료된 쿠폰 코드입니다.";
                } else {
                    // 3. 사용자가 이미 해당 쿠폰을 보유하고 있는지 확인 (사용 여부 무관하게 중복 등록 방지)
                    $stmt_check_user_coupon = $conn->prepare("SELECT user_coupon_id FROM UserCoupons WHERE user_id = ? AND coupon_id = ?");
                    $stmt_check_user_coupon->bind_param("ii", $user_id, $coupon_id);
                    $stmt_check_user_coupon->execute();
                    $result_check_user_coupon = $stmt_check_user_coupon->get_result();

                    if ($result_check_user_coupon->num_rows > 0) {
                        $register_error_message = "이미 보유하고 있거나 사용한 이력이 있는 쿠폰입니다.";
                    } else {
                        // 4. UserCoupons 테이블에 쿠폰 추가
                        $assigned_at = date('Y-m-d H:i:s');
                        $used_status = 0; // 미사용

                        $stmt_insert_user_coupon = $conn->prepare("INSERT INTO UserCoupons (user_id, coupon_id, used, assigned_at) VALUES (?, ?, ?, ?)");
                        $stmt_insert_user_coupon->bind_param("iiis", $user_id, $coupon_id, $used_status, $assigned_at);

                        if ($stmt_insert_user_coupon->execute()) {
                            $register_success_message = "쿠폰 \"".htmlspecialchars($entered_code_original)."\"이(가) 성공적으로 등록되었습니다!";
                        } else {
                            $register_error_message = "쿠폰 등록에 실패했습니다. 잠시 후 다시 시도해주세요.";
                        }
                        $stmt_insert_user_coupon->close();
                    }
                    $stmt_check_user_coupon->close();
                }
            } else {
                $register_error_message = "유효하지 않은 쿠폰 코드입니다.";
            }
            $stmt_check_coupon->close();
        } else {
            $register_error_message = "데이터베이스 연결 오류로 쿠폰을 등록할 수 없습니다.";
        }
    }
}

if (isset($conn) && $conn instanceof mysqli && !$conn->connect_error) {
    $sql_user_coupons = "SELECT
            C.discount_percent,
            C.valid_until
        FROM UserCoupons UC
        JOIN Coupons C ON UC.coupon_id = C.coupon_id
        WHERE UC.user_id = ? AND UC.used = 0
        ORDER BY C.valid_until ASC, UC.assigned_at DESC";

    if ($stmt_user_coupons = $conn->prepare($sql_user_coupons)) {
        $stmt_user_coupons->bind_param("i", $user_id);
        $stmt_user_coupons->execute();
        $result_user_coupons = $stmt_user_coupons->get_result();
        while ($row = $result_user_coupons->fetch_assoc()) {
            $coupons_list[] = $row;
        }
        $stmt_user_coupons->close();
    } else {
        // error_log("사용자 쿠폰 목록 조회 SQL 준비 실패: " . $conn->error);
    }
} else {
    // error_log("데이터베이스 연결 실패 - 쿠폰함 목록 조회");
}

?>
<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <title>쿠폰함</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <style>
    * {
      box-sizing: border-box;
    }

    body {
      font-family: 'Arial', sans-serif;
      background-color: #f9f9f9;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
    }

    .coupon-container {
      background-color: #fff;
      border: 1px solid #ddd;
      width: 100%;
      max-width: 350px;
      margin: 20px;
      padding: 20px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
      display: flex;
      flex-direction: column;
    }

    .page-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
        margin-bottom: 20px;
    }
    .page-header a {
        text-decoration: none;
        color: #333;
        font-size: 1.2em;
        padding: 5px;
    }
    .page-header h2 {
        margin: 0;
        font-size: 1.25em;
        text-align: center;
        flex-grow: 1;
    }
    .page-header span {
        width: 24px; 
        padding: 5px;
        visibility: hidden;
    }
    
    .coupon-card {
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 15px;
      background-color: #fff;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }

    .discount {
      font-size: 1.15em;
      color: #007bff;
      font-weight: bold;
      margin: 0 0 8px 0;
    }

    .desc {
      font-size: 0.9em;
      color: #555;
      margin: 0;
      line-height: 1.5;
    }

    .message { padding: 10px; margin-bottom: 15px; border-radius: 4px; font-size: 0.9em; text-align: center; }
    .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
    .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    .no-coupons { text-align: center; padding: 20px; color: #777; }
    
    .coupon-container hr {
        border: none;
        border-top: 1px solid #eee;
        margin: 20px 0;
    }

    .coupon-register-form {
      padding: 15px;
      background-color: #f9f9f9;
      border: 1px solid #e0e0e0;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    .coupon-register-form h3 {
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 1.1em;
      text-align: center;
      color: #333;
    }
    .coupon-register-form .form-group {
      margin-bottom: 10px;
    }
    .coupon-register-form input[type="text"] {
      width: 100%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      box-sizing: border-box;
      font-size: 0.95em;
    }
    .coupon-register-form button {
      width: 100%;
      padding: 10px 15px;
      background-color: #5cb85c;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 1em;
      font-weight: bold;
      transition: background-color 0.2s ease;
    }
    .coupon-register-form button:hover {
      background-color: #4cae4c;
    }

    h3 {
        font-size: 1.1em;
        text-align: center;
        margin-top: 0;
        margin-bottom: 15px;
        color: #333;
    }
  </style>
</head>

<body>
  <div class="coupon-container">
    <div class="page-header"
      style="display: flex; align-items: center; justify-content: space-between; padding: 0 0 10px 0; border-bottom: 1px solid #eee; margin-bottom: 15px;">
      <a href="../../auth/redirect-mypage.php" title="뒤로가기"
        style="text-decoration: none; color: #333; font-size: 1.2em; padding: 5px;">
        <i class="fas fa-arrow-left"></i>
      </a>
      <h2 style="margin: 0; font-size: 1.25em; text-align: center; flex-grow: 1;">쿠폰함</h2>
      <span style="width: 24px; padding: 5px;"></span>
    </div>

    <div class="coupon-register-form">
      <h3>쿠폰 코드 등록</h3>
      <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <div class="form-group">
          <input type="text" name="coupon_code_input" placeholder="쿠폰 코드를 입력하세요" required>
        </div>
        <button type="submit" name="register_coupon_code_submit">등록하기</button>
      </form>
      <?php if (!empty($register_success_message)): ?>
      <p class="message success" style="margin-top: 10px;">
        <?php echo $register_success_message; ?>
      </p>
      <?php endif; ?>
      <?php if (!empty($register_error_message)): ?>
      <p class="message error" style="margin-top: 10px;">
        <?php echo $register_error_message; ?>
      </p>
      <?php endif; ?>
    </div>
    <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
    <h3>보유 쿠폰 목록</h3>
    <?php if (!empty($coupons_list)): ?>
    <?php foreach ($coupons_list as $coupon): ?>
    <?php
          // ... (기존 할인 정보 및 설명 생성 로직) ...
          $discount_text = '';
          if (isset($coupon['discount_type'])) { // 이 부분은 Coupons 테이블 구조에 따라 달라집니다.
            if ($coupon['discount_type'] == 'amount' && !empty($coupon['discount_amount'])) {
                $discount_text = number_format($coupon['discount_amount']) . "원 할인";
            } elseif ($coupon['discount_type'] == 'percent' && !empty($coupon['discount_percent'])) {
                $percent_display = rtrim(rtrim(number_format($coupon['discount_percent'], 1), '0'), '.');
                $discount_text = $percent_display . "% 할인";
            } else { $discount_text = "할인 쿠폰"; }
          } else { // discount_type이 없는 경우 (현재 SELECT 쿼리에 맞춘 부분)
            if (!empty($coupon['discount_percent'])) {
                $percent_display = rtrim(rtrim(number_format($coupon['discount_percent'], 1), '0'), '.');
                $discount_text = $percent_display . "% 할인";
            } else { $discount_text = "사용 가능 쿠폰"; }
          }
          // coupon_name은 현재 SELECT 쿼리에서 가져오지 않으므로, 기본값을 사용합니다.
          $coupon_description = '할인 쿠폰'; // isset($coupon['coupon_name']) ? htmlspecialchars($coupon['coupon_name']) : '할인 쿠폰';
          $valid_until_formatted = isset($coupon['valid_until']) ? date("Y/m/d", strtotime($coupon['valid_until'])) : 'N/A';
        ?>
    <div class="coupon-card">
      <p class="discount">
        <?php echo htmlspecialchars($discount_text); ?>
      </p>
      <p class="desc">
        <?php echo htmlspecialchars($coupon_description); ?><br>
        <?php echo $valid_until_formatted; ?>까지 사용가능
      </p>
    </div>
    <?php endforeach; ?>
    <?php else: ?>
    <p class="no-coupons">사용 가능한 쿠폰이 없습니다.</p>
    <?php endif; ?>

  </div>
</body>

</html>