<?php
require_once 'includes/config.php';

try {
    // Koneksi ke database marketing
    $mkt_db = new PDO(
        "mysql:host={$config['mkt_db_host']};dbname={$config['mkt_db_name']}",
        $config['mkt_db_user'],
        $config['mkt_db_pass']
    );
    $mkt_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Mulai transaksi di kedua database
    $db->beginTransaction();
    $mkt_db->beginTransaction();

    // Ambil jumlah marketing dari db_auth (db_callv3sa)
    $stmt = $db_auth->query("SELECT COUNT(*) as total, GROUP_CONCAT(id) as ids FROM marketing WHERE deleted_at IS NULL");
    $marketing = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($marketing['total'] == 0) {
        throw new Exception("No marketing users available");
    }

    $marketing_ids = explode(',', $marketing['ids']);
    
    // Ambil nomor yang akan didistribusikan dari db_callv3
    $stmt = $db->query("SELECT * FROM target_numbers 
        WHERE pressed_button = '1' 
        AND status = 'Success'
        ORDER BY call_date");
    $numbers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($numbers)) {
        throw new Exception("No numbers available to share");
    }

    // Distribusi nomor
    $marketing_index = 0;
    foreach ($numbers as $number) {
        // Rotasi marketing_id
        $marketing_id = $marketing_ids[$marketing_index];
        $marketing_index = ($marketing_index + 1) % count($marketing_ids);

        // Insert ke tabel distributed_numbers
        $stmt = $mkt_db->prepare("INSERT INTO distributed_numbers 
            (marketing_id, phone_number, pressed_button, status, original_call_date) 
            VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            $marketing_id,
            $number['phone_number'],
            $number['pressed_button'],
            $number['status'],
            $number['call_date']
        ]);

        // Hapus dari tabel target_numbers
        $stmt = $db->prepare("DELETE FROM target_numbers WHERE id = ?");
        $stmt->execute([$number['id']]);
    }

    // Commit transaksi
    $db->commit();
    $mkt_db->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Successfully distributed ' . count($numbers) . ' numbers to ' . $marketing['total'] . ' marketers'
    ]);

} catch (Exception $e) {
    // Rollback jika terjadi error
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    if (isset($mkt_db) && $mkt_db->inTransaction()) {
        $mkt_db->rollBack();
    }

    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} 