<?php
session_start(); 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

include '../koneksi.php';
require '../vendor/autoload.php'; 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];

    // Periksa apakah email ada di tabel users
    $stmt = $conn->prepare("SELECT id_user FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $stmt->close();

        // Buat token unik dan set masa berlaku 1 jam
        $token = bin2hex(random_bytes(50));
        $expires_at = date("Y-m-d H:i:s", strtotime("+8 hour"));

        // Hapus token lama (jika ada)
        $stmt = $conn->prepare("DELETE FROM password_resets WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->close();

        // Simpan token baru
        $stmt = $conn->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $email, $token, $expires_at);
        $stmt->execute();
        $stmt->close();

        // Kirim email reset password menggunakan PHPMailer
        $reset_link = "https://portalumkm.com/lupa-password/reset_password.php?token=$token";

        $mail = new PHPMailer(true);

        try {
            // Konfigurasi SMTP
            $mail->isSMTP();
            $mail->Host = 'mail.portalumkm.com'; // Sesuaikan dengan penyedia hosting
            $mail->SMTPAuth = true;
            $mail->Username = 'admin@portalumkm.com'; 
            $mail->Password = 'Vwa,7[io.9D]'; // Ganti dengan password email admin
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587; // Atau cek port yang sesuai (465 untuk SSL, 587 untuk TLS)
            
            // Pengirim dan Penerima
            $mail->setFrom('admin@portalumkm.com', 'Support Portal UMKM');
            $mail->addAddress($email);


            // Konten email
            $mail->isHTML(true);
            $mail->Subject = "Permintaan Atur Ulang Kata Sandi Portal UMKM";
            $mail->Body = "
                            <p>Halo,</p>
                            <p>Kami menerima permintaan untuk mereset password akun Anda. Klik tombol di bawah untuk mengatur ulang password Anda:</p>
                            <p style='text-align: center;'>
                                <a href='$reset_link' 
                                  style='display: inline-block; padding: 12px 20px; font-size: 16px; color: #fff; background-color: #007bff; text-decoration: none; border-radius: 5px;'>
                                  Reset Password
                                </a>
                            </p>
                            <p>Jika Anda tidak merasa melakukan permintaan ini, abaikan saja email ini. Link ini akan kedaluwarsa dalam 1 jam.</p>
                            <p>Salam,<br>Tim Support</p>
                        ";
                        
            $mail->send();
            $_SESSION['success'] = "Cek email untuk mengatur ulang kata sandi.";
        } catch (Exception $e) {
            $_SESSION['error'] = "Email gagal dikirim: {$mail->ErrorInfo}";
        }
    } else {
        $_SESSION['error'] = "Email tidak ditemukan.";
    }

    // Redirect ke halaman login atau halaman lain
    header("Location: ../lupa-password");
    exit();
}
?>


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

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

  <title>Lupa 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="/" 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">Lupa Kata Sandi Akun?</h5>
                    <p class="text-center small">Masukkan email untuk mengatur ulang kata sandi</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="email" class="form-label">Email<span class="text-danger">*</span></label>
                        <input type="text" name="email" class="form-control" id="email" required>
                        <div class="invalid-feedback">Silahkan masukkan alamat email.</div>
                     </div>

                    <div class="col-12">
                      <button class="btn btn-primary w-100 rounded-pill" type="submit">Kirim Permintaan</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>