File size: 12,879 Bytes
e31284f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
<?php
/**

 * Payment API Endpoint

 * 

 * POST /api/payments/process

 * 

 * Accepts JSON payload to process student fee payments via external systems.

 * This endpoint uses the same internal payment logic as the web UI.

 * 

 * Request Format:

 * {

 *   "student_id": "string|integer",

 *   "teller_no": "string",

 *   "amount": number

 * }

 * 

 * Headers Required:

 * - Content-Type: application/json

 * - Authorization: Bearer <API_KEY> (if API_AUTH_ENABLED is true)

 */

// Set error reporting for production
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Include required files
require_once __DIR__ . '/../../db_config.php';
require_once __DIR__ . '/../../config/api_config.php';
require_once __DIR__ . '/../../includes/ApiValidator.php';
require_once __DIR__ . '/../../includes/PaymentProcessor.php';
require_once __DIR__ . '/../../includes/ReceiptGenerator.php';

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

// CORS headers (if enabled)
if (defined('API_CORS_ENABLED') && API_CORS_ENABLED) {
    header('Access-Control-Allow-Origin: ' . API_CORS_ORIGIN);
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');

    // Handle preflight requests
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }
}

/**

 * Send JSON response

 */
function sendResponse($data, $httpCode = 200)

{
    http_response_code($httpCode);
    echo json_encode($data, JSON_PRETTY_PRINT);
    exit;
}

/**

 * Log API request

 */
function logApiRequest($data, $response, $httpCode)

{
    if (!defined('API_LOG_ENABLED') || !API_LOG_ENABLED) {
        return;
    }

    $logDir = dirname(API_LOG_FILE);
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }

    $logEntry = [
        'timestamp' => date('Y-m-d H:i:s'),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'method' => $_SERVER['REQUEST_METHOD'] ?? 'unknown',
        'request' => $data,
        'response' => $response,
        'http_code' => $httpCode
    ];

    file_put_contents(
        API_LOG_FILE,
        json_encode($logEntry) . PHP_EOL,
        FILE_APPEND
    );
}

// Main execution
try {
    // Initialize validator
    $apiKeys = defined('API_AUTH_ENABLED') && API_AUTH_ENABLED ? array_keys(API_KEYS) : [];
    $validator = new ApiValidator($pdo, $apiKeys);

    // Step 1: Validate request (method, headers, auth)
    $requestValidation = $validator->validateRequest();
    if (!$requestValidation['valid']) {
        $response = [
            'status' => 'error',
            'message' => $requestValidation['error']
        ];
        logApiRequest([], $response, $requestValidation['http_code']);
        sendResponse($response, $requestValidation['http_code']);
    }

    // Step 2: Parse JSON payload
    $payloadValidation = $validator->parseJsonPayload();
    if (!$payloadValidation['valid']) {
        $response = [
            'status' => 'error',
            'message' => $payloadValidation['error']
        ];
        logApiRequest([], $response, $payloadValidation['http_code']);
        sendResponse($response, $payloadValidation['http_code']);
    }

    $requestData = $payloadValidation['data'];

    // Step 3: Validate required fields
    $fieldValidation = $validator->validatePaymentRequest($requestData);
    if (!$fieldValidation['valid']) {
        $response = [
            'status' => 'error',
            'message' => 'Validation failed',
            'errors' => $fieldValidation['errors']
        ];
        logApiRequest($requestData, $response, $fieldValidation['http_code']);
        sendResponse($response, $fieldValidation['http_code']);
    }

    // Sanitize input
    $sanitizedData = $validator->sanitizeInput($requestData);

    // Step 4: Validate student exists
    $studentValidation = $validator->validateStudentExists($sanitizedData['student_id']);
    if (!$studentValidation['valid']) {
        $response = [
            'status' => 'error',
            'message' => $studentValidation['error']
        ];
        logApiRequest($requestData, $response, $studentValidation['http_code']);
        sendResponse($response, $studentValidation['http_code']);
    }

    $student = $studentValidation['student'];

    // Add level_name for receipt
    $result['data']['level_name'] = $student['level_name'] ?? '';

    // Step 5: Validate teller number
    $tellerValidation = $validator->validateTellerNumber($sanitizedData['teller_no']);
    if (!$tellerValidation['valid']) {
        $response = [
            'status' => 'error',
            'message' => $tellerValidation['error']
        ];
        logApiRequest($requestData, $response, $tellerValidation['http_code']);
        sendResponse($response, $tellerValidation['http_code']);
    }

    $teller = $tellerValidation['teller'];

    // Step 6: Validate amount doesn't exceed unreconciled amount
    if ($sanitizedData['amount'] > $teller['unreconciled_amount']) {
        $response = [
            'status' => 'error',
            'message' => 'Amount exceeds unreconciled amount on teller',
            'errors' => [
                'amount' => 'Requested amount (' . number_format($sanitizedData['amount'], 2) .
                    ') exceeds available unreconciled amount (' .
                    number_format($teller['unreconciled_amount'], 2) . ')'
            ]
        ];
        logApiRequest($requestData, $response, 400);
        sendResponse($response, 400);
    }

    // Step 7: Get outstanding fees for the student
    $processor = new PaymentProcessor($pdo);
    $outstandingFees = $processor->getOutstandingFees($student['id']);

    if (empty($outstandingFees)) {
        $response = [
            'status' => 'error',
            'message' => 'No outstanding fees found for this student'
        ];
        logApiRequest($requestData, $response, 400);
        sendResponse($response, 400);
    }

    // Step 8: Prepare payment parameters
    // The API will automatically allocate the payment to outstanding fees (oldest first)
    $paymentParams = [
        'student_id' => $student['id'],
        'student_code' => $student['student_code'],
        'selected_fees' => $outstandingFees,
        'teller_number' => $sanitizedData['teller_no'],
        'payment_date' => $sanitizedData['payment_date'], // Use provided date
        'amount_to_use' => $sanitizedData['amount'],
        'source' => 'api' // Mark this payment as API-initiated
    ];

    // Step 9: Process payment using the internal payment logic
    $result = $processor->processPayment($paymentParams);

    if ($result['success']) {
        // Fetch ALL fees for comprehensive receipt (matching web interface behavior)
        // This ensures the receipt shows complete fee picture, not just current transaction
        $studentId = $result['data']['student_id'];
        $paymentDate = $result['data']['payment_date'];
        $receiptNo = $result['data']['receipt_no'];

        // Fetch all fees from receivables
        $sqlFees = "SELECT ar.fee_id, ar.actual_value as amount_billed,

                           ar.academic_session, ar.term_of_session,

                           sf.description as fee_description

                    FROM tb_account_receivables ar

                    JOIN tb_account_school_fees sf ON ar.fee_id = sf.id

                    WHERE ar.student_id = :sid

                    ORDER BY ar.academic_session ASC, ar.term_of_session ASC";

        $stmtFees = $pdo->prepare($sqlFees);
        $stmtFees->execute(['sid' => $studentId]);
        $allFees = $stmtFees->fetchAll(PDO::FETCH_ASSOC);

        $allocations = [];
        $receiptTotalPaid = 0;

        foreach ($allFees as $fee) {
            // Calculate Paid To Date (up to this receipt's date)
            $sqlPaid = "SELECT SUM(amount_paid) as total_paid

                        FROM tb_account_payment_registers

                        WHERE student_id = :sid

                          AND fee_id = :fid

                          AND academic_session = :as

                          AND term_of_session = :ts

                          AND payment_date <= :pd";

            $stmtPaid = $pdo->prepare($sqlPaid);
            $stmtPaid->execute([
                'sid' => $studentId,
                'fid' => $fee['fee_id'],
                'as' => $fee['academic_session'],
                'ts' => $fee['term_of_session'],
                'pd' => $paymentDate
            ]);
            $paidResult = $stmtPaid->fetch(PDO::FETCH_ASSOC);
            $paidToDate = floatval($paidResult['total_paid'] ?? 0);

            // Calculate Amount paid IN THIS RECEIPT (for total calculation)
            $sqlReceiptPay = "SELECT SUM(amount_paid) as receipt_paid

                              FROM tb_account_payment_registers

                              WHERE receipt_no = :rno

                                AND fee_id = :fid

                                AND academic_session = :as

                                AND term_of_session = :ts";
            $stmtReceiptPay = $pdo->prepare($sqlReceiptPay);
            $stmtReceiptPay->execute([
                'rno' => $receiptNo,
                'fid' => $fee['fee_id'],
                'as' => $fee['academic_session'],
                'ts' => $fee['term_of_session']
            ]);
            $receiptPayResult = $stmtReceiptPay->fetch(PDO::FETCH_ASSOC);
            $paidInReceipt = floatval($receiptPayResult['receipt_paid'] ?? 0);

            $receiptTotalPaid += $paidInReceipt;
            $balance = floatval($fee['amount_billed']) - $paidToDate;

            // Show if (Balance > 0) OR (PaidInReceipt > 0)
            // This filters out old fully paid fees but keeps current payments
            if ($balance > 0.001 || $paidInReceipt > 0.001) {
                $allocations[] = [
                    'description' => $fee['fee_description'],
                    'academic_session' => $fee['academic_session'],
                    'term_of_session' => $fee['term_of_session'],
                    'amount_billed' => floatval($fee['amount_billed']),
                    'amount' => $paidInReceipt,
                    'total_paid_to_date' => $paidToDate,
                    'balance' => $balance
                ];
            }
        }

        // Prepare comprehensive receipt data
        $receiptData = [
            'receipt_no' => $receiptNo,
            'student_name' => $student['full_name'],
            'student_code' => $student['student_code'],
            'level_name' => $student['level_name'] ?? '',
            'payment_date' => $paymentDate,
            'total_paid' => $receiptTotalPaid,
            'allocations' => $allocations
        ];

        // Generate receipt with complete fee information
        $generator = new ReceiptGenerator();
        $receiptBase64 = $generator->generateBase64($receiptData);

        $response = [
            'status' => 'success',
            'message' => $result['message'],
            'data' => [
                'student_id' => $result['data']['student_id'],
                'teller_no' => $result['data']['teller_no'],
                'amount' => $result['data']['total_paid'],
                'payment_id' => $result['data']['transaction_id'],
                'receipt_no' => $result['data']['receipt_no'],
                'payment_date' => $result['data']['payment_date'],
                'receipt_image' => $receiptBase64,
                'fees_settled' => array_map(function ($allocation) {
                    return [
                        'fee_description' => $allocation['description'],
                        'session' => $allocation['academic_session'],
                        'term' => $allocation['term_of_session'],
                        'amount' => $allocation['amount']
                    ];
                }, $result['data']['allocations'])
            ]
        ];
        logApiRequest($requestData, $response, 201);
        sendResponse($response, 201);
    } else {
        $response = [
            'status' => 'error',
            'message' => $result['message']
        ];
        logApiRequest($requestData, $response, 500);
        sendResponse($response, 500);
    }

} catch (Exception $e) {
    $response = [
        'status' => 'error',
        'message' => 'Internal server error',
        'error_detail' => $e->getMessage() // Remove in production
    ];
    logApiRequest($requestData ?? [], $response, 500);
    sendResponse($response, 500);
}