<?php
// process_payment.php
session_start();
require_once '../config/db_connect.php';

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

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

$user = $_SESSION['user'];
$user_role = $user['role'] ?? 'cashier';

// Check permissions
if (!in_array($user_role, ['admin', 'pharmacist'])) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit;
}

$sale_id = intval($_POST['sale_id'] ?? 0);
$amount = floatval($_POST['amount'] ?? 0);
$payment_method = $_POST['payment_method'] ?? 'CASH';

if ($sale_id <= 0 || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid payment details']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    // Get sale details
    $stmt = $pdo->prepare("SELECT total, paid, shop_id FROM sales WHERE id = ?");
    $stmt->execute([$sale_id]);
    $sale = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$sale) {
        throw new Exception("Sale not found.");
    }
    
    $balance = $sale['total'] - $sale['paid'];
    
    // Validate amount
    if ($amount > $balance) {
        throw new Exception("Payment amount cannot exceed the balance of " . number_format($balance, 2));
    }
    
    $new_paid = $sale['paid'] + $amount;
    $new_balance = $sale['total'] - $new_paid;
    $new_status = ($new_balance <= 0) ? 'paid' : 'partially_paid';
    
    // Update sale
    $stmt = $pdo->prepare("UPDATE sales SET paid = ?, status = ? WHERE id = ?");
    $stmt->execute([$new_paid, $new_status, $sale_id]);
    
    // Record payment
    $stmt = $pdo->prepare("INSERT INTO payments (sale_id, amount, method, created_by, shop_id, paid_at) 
                           VALUES (?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$sale_id, $amount, $payment_method, $user['id'], $sale['shop_id']]);
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Payment of ' . number_format($amount, 2) . ' recorded successfully',
        'sale_id' => $sale_id,
        'new_paid' => number_format($new_paid, 2),
        'new_balance' => number_format($new_balance, 2),
        'new_status' => $new_status
    ]);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}