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

ini_set('log_errors', 1);              // Enable PHP error logging
ini_set('error_log', __DIR__ . '/php_error.log'); // Log file path (in same folder)

session_start();
header('Content-Type: application/json');
require "conn.php";

/* 🪵 Log Setup */
$logFile = __DIR__ . '/product_action.log';
function logMsg($msg) {
    global $logFile;
    file_put_contents($logFile, '[' . date('Y-m-d H:i:s') . "] " . $msg . "\n", FILE_APPEND);
}

$response = ['success' => false, 'message' => 'Invalid request'];

$action = $_POST['action'] ?? '';

/* 🔒 Optional session check */
$key = md5(date("Y-m-d") . ":" . $_SERVER['REMOTE_ADDR']);
if (!isset($_SESSION['aW1iZXN0cmEuY29tLm15']) || $_SESSION['aW1iZXN0cmEuY29tLm15'] != $key) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

/* 🚀 Save (Add or Update) */
if ($action === 'save') {
    $id             = intval($_POST['id'] ?? 0);
    $product_name   = trim((string)($_POST['product_name'] ?? ''));
    $sku            = trim((string)($_POST['sku'] ?? ''));
    $price          = floatval($_POST['price'] ?? 0);
    $cost_price     = floatval($_POST['cost_price'] ?? 0);
    $discount_type  = (string)($_POST['discount_type'] ?? 'NONE');
    $discount_value = floatval($_POST['discount_value'] ?? 0);
    $description    = trim((string)($_POST['description'] ?? ''));

    // 🪵 Log input data
    //logMsg("Action: save | ID: $id | Name: $product_name | SKU: $sku | Price: $price | Cost: $cost_price | DiscountType: $discount_type | DiscountValue: $discount_value | Description: $description");

    // 🧩 Validate
    if ($product_name === '') {
        echo json_encode(['success' => false, 'message' => 'Product name is required']);
        //logMsg("❌ Validation failed: Product name missing");
        exit;
    }

    // 📸 Handle Image Upload (if any)
    $imgName = '';
    if (!empty($_FILES['img']['name'])) {
        $ext = strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'heic'];
        if (!in_array($ext, $allowed)) {
            echo json_encode(['success' => false, 'message' => 'Invalid image format']);
            //logMsg("❌ Invalid image format: $ext");
            exit;
        }
        $imgName = uniqid('prod_') . '.' . $ext;
        $uploadPath = __DIR__ . "/uploads/products/" . $imgName;
        if (!move_uploaded_file($_FILES['img']['tmp_name'], $uploadPath)) {
            echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
            //logMsg("❌ Failed to upload image: " . $_FILES['img']['name']);
            exit;
        }
        logMsg("✅ Image uploaded: $imgName");
    }

    // If editing, keep old image if new not uploaded
    if ($id > 0 && $imgName === '') {
        $q = mysqli_query($con, "SELECT img FROM products WHERE id='$id'");
        $r = mysqli_fetch_assoc($q);
        $imgName = $r['img'] ?? '';
        //logMsg("ℹ️ Keeping old image: $imgName");
    }

    // 🛠️ Add or Update
    if ($id > 0) {
        $stmt = $con->prepare("
            UPDATE products 
            SET product_name=?, sku=?, price=?, cost_price=?, discount_type=?, discount_value=?, description=?, img=? 
            WHERE id=?
        ");
        $stmt->bind_param("ssddssssi", $product_name, $sku, $price, $cost_price, $discount_type, $discount_value, $description, $imgName, $id);
        $ok = $stmt->execute();
        //logMsg("🧾 Update SQL executed: " . ($ok ? "✅ Success" : "❌ Error: {$stmt->error}"));
        $stmt->close();
        $response = $ok
            ? ['success' => true, 'message' => '✅ Product updated successfully']
            : ['success' => false, 'message' => '❌ Failed to update product'];
    } else {
        $stmt = $con->prepare("
            INSERT INTO products (product_name, sku, price, cost_price, discount_type, discount_value, description, img, created_at)
            VALUES (?,?,?,?,?,?,?,?,NOW())
        ");
        $stmt->bind_param("ssddssss", $product_name, $sku, $price, $cost_price, $discount_type, $discount_value, $description, $imgName);
        $ok = $stmt->execute();
        //logMsg("🧾 Insert SQL executed: " . ($ok ? "✅ Success" : "❌ Error: {$stmt->error}"));
        $stmt->close();
        $response = $ok
            ? ['success' => true, 'message' => '✅ Product added successfully']
            : ['success' => false, 'message' => '❌ Failed to add product'];
    }
}

/* 🗑️ Delete */
elseif ($action === 'delete') {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid product ID']);
        //logMsg("❌ Delete failed: Invalid ID $id");
        exit;
    }

    // 🧹 Delete image if exists
    $res = mysqli_query($con, "SELECT img FROM products WHERE id='$id'");
    $row = mysqli_fetch_assoc($res);
    if (!empty($row['img']) && file_exists(__DIR__ . "/uploads/products/" . $row['img'])) {
        @unlink(__DIR__ . "/uploads/products/" . $row['img']);
        //logMsg("🧹 Deleted image: " . $row['img']);
    }

    // 🗑️ Delete record
    $del = mysqli_query($con, "DELETE FROM products WHERE id='$id'");
    //logMsg("🗑️ Delete SQL executed: " . ($del ? "✅ Success" : "❌ Failed"));
    $response = $del
        ? ['success' => true, 'message' => '✅ Product deleted successfully']
        : ['success' => false, 'message' => '❌ Failed to delete product'];
}

//logMsg("📦 Final response: " . json_encode($response));
echo json_encode($response);
?>
