<?php
session_start();
include '../koneksi.php';

if (!isset($_GET['token'])) {
    die("Token tidak valid.");
}

$token = $_GET['token'];

// Periksa apakah token valid dan belum kadaluarsa
$stmt = $conn->prepare("SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW()");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Token tidak valid atau telah kadaluarsa.");
}

$row = $result->fetch_assoc();
$email = $row['email']; // Ambil email dari token
$stmt->close();

// Jika form disubmit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // Validasi password
    if (strlen($password) < 8) {
        $_SESSION['error'] = "Kata Sandi minimal 8 karakter.";
    } elseif ($password !== $confirm_password) {
        $_SESSION['error'] = "Konfirmasi kata Sandi tidak cocok.";
    } else {
        // Hash password baru
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        // Update password di tabel users
        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
        $stmt->bind_param("ss", $hashed_password, $email);
        $stmt->execute();
        $stmt->close();

        // Hapus token agar tidak bisa digunakan lagi
        $stmt = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->close();

        $_SESSION['success'] = "Kata Sandi berhasil diubah. Silakan masuk.";
        header("Location: ../login");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Atur Ulang Kata Sandi | Portal UMKM</title>
  <meta content="" name="description">
  <meta content="" name="keywords">
  <meta name="robots" content="noindex">

  <!-- Favicons -->
  <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="../assets/template/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/template/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/template/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/template/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/template/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/template/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/template/vendor/simple-datatables/style.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="../assets/template/css/style.css" rel="stylesheet">

</head>

<body>

  <main>
    <div class="container">

      <section class="section register min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
        <div class="container">
          <div class="row justify-content-center">
            <div class="col-lg-4 col-md-6 d-flex flex-column align-items-center justify-content-center">

              <div class="d-flex justify-content-center py-4">
                <a href="index.html" class="logo d-flex align-items-center w-auto">
                  <img src="../assets/img/logo.png" alt="">
                  <span class="d-none d-lg-block">Portal UMKM</span>
                </a>
              </div><!-- End Logo -->

              <div class="card mb-3">

                <div class="card-body">

                  <div class="pt-4 pb-2">
                    <h5 class="card-title text-center pb-0 fs-4">Atur Ulang Kata Sandi</h5>
                    <p class="text-center small">Masukkan kata sandi baru</p>
                  </div>

                  <?php if (isset($_SESSION['success'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                      <?= $_SESSION['success']; ?>
                      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['success']); ?>
                  <?php endif; ?>

                  <?php if (isset($_SESSION['error'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                      <?= $_SESSION['error']; ?>
                      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error']); ?>
                  <?php endif; ?>

                  <form class="row g-3 needs-validation" method="post" novalidate>

                    <div class="col-12">
                      <label for="password" class="form-label">Kata Sandi Baru<span class="text-danger">*</span></label>
                        <input type="password" name="password" class="form-control" id="password" required>
                        <div class="invalid-feedback">Silahkan masukkan kata sandi barul.</div>
                     </div>

                     <div class="col-12">
                      <label for="password" class="form-label">Konfirmasi Kata Sandi Baru<span class="text-danger">*</span></label>
                        <input type="password" name="confirm_password" class="form-control" id="confirm_password" required>
                        <div class="invalid-feedback">Silahkan masukkan konfirmasi kata sandi barul.</div>
                     </div>

                    <div class="col-12">
                      <button class="btn btn-primary w-100 rounded-pill" type="submit">Atur Kata Sandi</button>
                    </div>
                    <div class="col-12">
                      <p class="small mb-0">Sudah Punya Akun? <a href="../login/">Masuk Sekarang</a></p>
                    </div>
                  </form>

                </div>
              </div>

              <div class="credits">
                <!-- All the links in the footer should remain intact. -->
                <!-- You can delete the links only if you purchased the pro version. -->
                <!-- Licensing information: https://bootstrapmade.com/license/ -->
                <!-- Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/nice-admin-bootstrap-admin-html-template/ -->
                <!-- Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> -->
              </div>

            </div>
          </div>
        </div>

      </section>

    </div>
  </main><!-- End #main -->

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="../assets/template/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="../assets/template/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/template/vendor/chart.js/chart.umd.js"></script>
  <script src="../assets/template/template/vendor/echarts/echarts.min.js"></script>
  <script src="../assets/template/vendor/quill/quill.js"></script>
  <script src="../assets/template/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="../assets/template/vendor/tinymce/tinymce.min.js"></script>
  <script src="../assets/template/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="../assets/template/js/main.js"></script>

</body>

</html>