<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('stock_view');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

$pdo = getDB();

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$new_status = trim($_POST['status'] ?? '');

if (!$id || !$new_status) {
    echo json_encode(['success' => false, 'message' => 'ID and status are required.']);
    exit;
}

$valid_statuses = ['Available', 'Sold', 'Returned', 'Damaged', 'Warranty Claim'];
if (!in_array($new_status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status value.']);
    exit;
}

// Get current IMEI record
$stmt = $pdo->prepare("SELECT * FROM product_imei WHERE id = ?");
$stmt->execute([$id]);
$imei = $stmt->fetch();

if (!$imei) {
    echo json_encode(['success' => false, 'message' => 'IMEI record not found.']);
    exit;
}

$old_status = $imei['status'];

// Validate: cannot change Sold back to Available (must use return workflow)
if ($old_status === 'Sold' && $new_status === 'Available') {
    echo json_encode(['success' => false, 'message' => 'Cannot change status from Sold to Available directly. Please use the return workflow.']);
    exit;
}

try {
    $stmt = $pdo->prepare("UPDATE product_imei SET status = ? WHERE id = ?");
    $stmt->execute([$new_status, $id]);
    logActivity('Updated IMEI Status', 'Products', $id, 'IMEI ' . $imei['imei_number'] . ' status changed from ' . $old_status . ' to ' . $new_status);
    echo json_encode(['success' => true, 'message' => 'IMEI status updated successfully.']);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
