<?php
session_start();
include 'layouts/dbconn.php';

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['invoice_id']) && isset($_POST['status'])) {
    $invoice_id = intval($_POST['invoice_id']);
    $status = $_POST['status'];
    
    // Validate status
    $valid_statuses = ['DRAFT', 'SENT', 'PAID', 'PARTIAL', 'OVERDUE', 'CANCELLED'];
    if (!in_array($status, $valid_statuses)) {
        echo json_encode(['success' => false, 'message' => 'Invalid status']);
        exit();
    }
    
    // Update invoice status
    $update_sql = "UPDATE invoices SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE invoice_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("si", $status, $invoice_id);
    
    if ($stmt->execute()) {
        // Log the activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values) 
                   VALUES (?, 'UPDATE', 'invoices', ?, '', ?)";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("iss", $user_id, $invoice_id, $status);
        $log_stmt->execute();
        
        echo json_encode(['success' => true, 'message' => 'Invoice status updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}

$conn->close();
?>