<?php 
include 'config.php'; 
if(!isset($_SESSION['user_id'])) exit();

$id = (int)$_GET['id'];
$agency_id = $_SESSION['agency_id'];

$res = $conn->query("SELECT p.*, c.name FROM payments p JOIN clients c ON p.client_id = c.id WHERE p.id = $id AND p.agency_id = $agency_id");
$data = $res->fetch_assoc();

if(!$data) die("Transaction not found.");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Entry</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background: #f8f9fc; padding: 50px; }
        .form-card { background: #fff; max-width: 500px; margin: auto; padding: 30px; border-radius: 15px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); }
        input, select { width: 100%; padding: 12px; margin: 10px 0; border: 1px solid #ddd; border-radius: 10px; }
        .btn { background: #4e73df; color: white; padding: 15px; border: none; width: 100%; border-radius: 10px; cursor: pointer; font-weight: 600; }
    </style>
</head>
<body>
    <div class="form-card">
        <h2>Edit Ledger Entry</h2>
        <p>Client: <b><?php echo $data['name']; ?></b></p>
        <hr style="margin:20px 0; border:0; border-top:1px solid #eee;">
        
        <form action="handle_transaction.php" method="POST">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" value="<?php echo $id; ?>">
            <input type="hidden" name="client_id" value="<?php echo $data['client_id']; ?>">
            
            <label>Amount (PKR)</label>
            <input type="number" name="amount" value="<?php echo $data['amount']; ?>" required>
            
            <label>Transaction Type</label>
            <select name="transaction_type">
                <option value="Debit" <?php if($data['transaction_type'] == 'Debit') echo 'selected'; ?>>Debit (+ Charge)</option>
                <option value="Credit" <?php if($data['transaction_type'] == 'Credit') echo 'selected'; ?>>Credit (- Payment)</option>
            </select>

            <label>Description</label>
            <input type="text" name="notes" value="<?php echo $data['notes']; ?>" required>
            
            <label>Date</label>
            <input type="date" name="p_date" value="<?php echo $data['payment_date']; ?>" required>
            
            <button type="submit" class="btn">Update Record</button>
            <a href="view_client_ledger.php?id=<?php echo $data['client_id']; ?>" style="display:block; text-align:center; margin-top:15px; color:#64748b; text-decoration:none;">Cancel</a>
        </form>
    </div>
</body>
</html>