<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("../config/theconfig.php");

// Set header to indicate a JSON response
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['customerid'])) {
    echo json_encode(['status' => 'error', 'message' => "User not logged in. Please log in again."]);
    exit();
}

$customerid = $_SESSION['customerid'];
$dts = date("Y-m-d H:i:s");

// Update last login
$stmt_lastlogin = $con->prepare("UPDATE customers SET lastlogin=? WHERE customerid=?");
$stmt_lastlogin->bind_param("si", $dts, $customerid);
$stmt_lastlogin->execute();

// Handle profile image upload
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file = $_FILES['product_img1'] ?? null;

    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['status' => 'error', 'message' => "No file was uploaded or an error occurred."]);
        exit();
    }

    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 2 * 1024 * 1024; // 2MB

    // Validate file type
    if (!in_array($file['type'], $allowed_types)) {
        echo json_encode(['status' => 'error', 'message' => "Only JPG, PNG, GIF, and WebP are allowed."]);
        exit();
    }

    // Validate file size
    if ($file['size'] > $max_size) {
        echo json_encode(['status' => 'error', 'message' => "File is too large. Max 2MB allowed."]);
        exit();
    }
    
    
    $upload_dir = dirname(__DIR__) . "assets/images/users/";
    
    
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $new_filename = uniqid('profile_') . '.' . $file_ext;
    $upload_path = $upload_dir . $new_filename;

    if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
        echo json_encode(['status' => 'error', 'message' => "Upload failed. Check folder permissions."]);
        exit();
    }

    // Fetch customer record to delete old image
    $stmt_customer = $con->prepare("SELECT image FROM customers WHERE customerid=?");
    $stmt_customer->bind_param("i", $customerid);
    $stmt_customer->execute();
    $result_customer = $stmt_customer->get_result();
    $rowrec = $result_customer->fetch_assoc();

    if ($rowrec && !empty($rowrec['image'])) {
        $old_image_path = $upload_dir . $rowrec['image'];
        if (file_exists($old_image_path)) {
            unlink($old_image_path);
        }
    }

    // Update DB with new image
    $stmt = $con->prepare("UPDATE customers SET image=? WHERE customerid=?");
    $stmt->bind_param("si", $new_filename, $customerid);
    $stmt->execute();
    
    echo json_encode(['status' => 'success', 'message' => 'Profile image uploaded successfully!']);
    exit();
}
?>