<?php
session_start();
require 'config/koneksi.php';
$error = "";
$success = "";

if (isset($_COOKIE['fe_remember_email'])) {
    $_SESSION['login'] = 1;
    $_SESSION['Email'] = $_COOKIE['fe_remember_email'];
    $_SESSION['FullName'] = $_COOKIE['fe_remember_fullname'] ?? 'Profile';
    $_SESSION['UserID'] = $_COOKIE['fe_remember_userid'] ?? '';
    header("Location: index.php");
    exit();
}

if (isset($_POST['login'])) {
    $email = trim($_POST['email']);
    $password = isset($_POST['password']) ? $_POST['password'] : "";

    if (empty($email)) {
        $error = "Email tidak boleh kosong.";
    }
    elseif (empty($password)) {
        $error = "Password tidak boleh kosong.";
    }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Format email tidak valid.";
    }
    elseif (strlen($password) < 8) {
        $error = "Password harus minimal 8 karakter.";
    }
    elseif (!preg_match('/\d/', $password)) {
        $error = "Password harus mengandung angka.";
    }
    elseif (!preg_match('/[a-zA-Z]/', $password)) {
        $error = "Password harus mengandung huruf.";
    }
    else {
        $stmt = $conn->prepare("SELECT member_id, email, password, nama FROM members WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $error = "Email tidak terdaftar.";
        } else {
            $user = $result->fetch_assoc();
            if (md5($password) !== $user['password']) {
                $error = "Password salah.";
            } else {
                $_SESSION['login'] = 1;
                $_SESSION['UserID'] = $user['member_id'];
                $_SESSION['Email'] = $user['email'];
                $_SESSION['FullName'] = $user['nama'];

                if (isset($_POST['remember'])) {
                    setcookie("fe_remember_email", $user['email'], time() + (86400 * 30), "/");
                    setcookie("fe_remember_fullname", $user['nama'], time() + (86400 * 30), "/");
                    setcookie("fe_remember_userid", $user['member_id'], time() + (86400 * 30), "/");
                } else {
                    setcookie("fe_remember_email", "", time() - 3600, "/");
                    setcookie("fe_remember_fullname", "", time() - 3600, "/");
                    setcookie("fe_remember_userid", "", time() - 3600, "/");
                }

                header("Location: index.php");
                exit();
            }
        }
        $stmt->close();
    }
}
?>
