<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: documents.php');
    exit;
}

$id = $_POST['id'] ?? 0;
$new_status = $_POST['status'] ?? '';

$allowed_statuses = ['draft', 'sent', 'paid', 'partially_paid', 'overdue', 'accepted', 'rejected'];
if (!in_array($new_status, $allowed_statuses)) {
    $_SESSION['error'] = 'Invalid status.';
    header("Location: documents.php");
    exit;
}

$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT id FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();
if (!$company) {
    header('Location: settings.php');
    exit;
}

$stmt = $pdo->prepare("UPDATE documents SET status = ? WHERE id = ? AND company_id = ?");
$stmt->execute([$new_status, $id, $company['id']]);

$_SESSION['success'] = 'Document status updated successfully.';
header('Location: document-view.php?id=' . $id);
?>