File size: 4,199 Bytes
0dff816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

// Include database configuration
require_once '../../db.php';

// Get user data from session
$user_id = $_SESSION['user_id'] ?? null;
$current_balance = $_SESSION['balance'];

if (!$user_id) {
    echo json_encode(['success' => false, 'message' => 'User not identified']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = filter_input(INPUT_POST, 'product_id', FILTER_SANITIZE_NUMBER_INT);
    
    try {
        // Start transaction
        $pdo->beginTransaction();
        
        // Get product details
        $stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? AND is_active = TRUE");
        $stmt->execute([$product_id]);
        $product = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$product) {
            throw new Exception("Product not available.");
        }
        
        // Check if user has sufficient balance
        if ($current_balance < $product['price']) {
            throw new Exception("Insufficient balance to purchase this product. You need KES " . 
                               number_format($product['price'] - $current_balance, 2) . " more.");
        }
        
        // Deduct product price from user's balance
        $new_balance = $current_balance - $product['price'];
        $stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
        $stmt->execute([$new_balance, $user_id]);
        
        // Record the transaction
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, balance_after) VALUES (?, 'product_purchase', ?, ?, ?)");
        $stmt->execute([
            $user_id, 
            $product['price'], 
            "Purchased: " . $product['name'],
            $new_balance
        ]);
        
        // Add to user's products
        $stmt = $pdo->prepare("INSERT INTO user_products (user_id, product_id, purchase_price, cashback_received) VALUES (?, ?, ?, ?)");
        $stmt->execute([$user_id, $product_id, $product['price'], $product['cashback_amount']]);
        
        // If there's cashback, process it
        if ($product['cashback_amount'] > 0) {
            $cashback_balance = $new_balance + $product['cashback_amount'];
            $stmt = $pdo->prepare("UPDATE users SET balance = ?, rewards = rewards + ? WHERE id = ?");
            $stmt->execute([$cashback_balance, $product['cashback_amount'], $user_id]);
            
            // Record cashback transaction
            $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, balance_after) VALUES (?, 'cashback', ?, ?, ?)");
            $stmt->execute([
                $user_id, 
                $product['cashback_amount'], 
                "Cashback for: " . $product['name'],
                $cashback_balance
            ]);
            
            $new_balance = $cashback_balance;
        }
        
        // Update user package if this is a package product
        if (stripos($product['name'], 'package') !== false || stripos($product['name'], 'bundle') !== false) {
            $stmt = $pdo->prepare("UPDATE users SET package = ? WHERE id = ?");
            $stmt->execute([$product['name'], $user_id]);
            
            // Update session data
            $_SESSION['package'] = $product['name'];
        }
        
        // Update session balance
        $_SESSION['balance'] = $new_balance;
        
        // Commit transaction
        $pdo->commit();
        
        // Return success response
        echo json_encode([
            'success' => true, 
            'message' => 'Product purchased successfully!',
            'new_balance' => $new_balance,
            'product_name' => $product['name'],
            'redirect_url' => 'package-' . strtolower(str_replace(' ', '-', $product['name'])) . '.php'
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}
?>