<?php
session_start();
include "koneksi.php";

if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['id'];

$foto = $_FILES['foto']['name'];
$tmp  = $_FILES['foto']['tmp_name'];

$ext = strtolower(pathinfo($foto, PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png'];

if (!in_array($ext, $allowed)) {
    header("Location: upload_foto.php?error=type");
    exit;
}

// rename file
$nama_baru = "foto_" . time() . "." . $ext;
$upload_path = "uploads/" . $nama_baru;

if (move_uploaded_file($tmp, $upload_path)) {

    // update database
    mysqli_query($koneksi, 
        "UPDATE user SET foto='$nama_baru' WHERE id='$user_id'"
    );

    // kembali dengan status sukses agar sweetalert tampil
    header("Location: upload_foto.php?success=1");
    exit;

} else {
    header("Location: upload_foto.php?error=upload");
    exit;
}
?>
