<commit_before><?php
namespace StudentRND\Http\Controllers;

use \Carbon\Carbon;
use \StudentRND\Models;

class DonateController extends \StudentRND\Http\Controller {
    private $donation_info;

    public function getIndex()
    {
        if (\Input::has('utm_campaign')) {
            \Session::set('donate_campaign', \Input::get('utm_campaign'));
        }
        return $this->makeDonationPage();
    }

    public function postIndex()
    {
        if (\Input::get('payment_method') === 'stripe' && \Input::get('frequency') === 'monthly') {
            return $this->stripeCheckoutRecurring();
        } else if (\Input::get('payment_method') === 'stripe' && \Input::get('frequency') === 'onetime') {
            return $this->stripeCheckoutOneTime();
        } else if (\Input::get('payment_method') === 'dwolla' && \Input::get('frequency') !== 'monthly') {
            return $this->dwollaCheckout();
        } else {
            return $this->makeDonationPage();
        }
    }

    public function getReceipt()
    {
        return \View::make('pages/donate/receipt', [
            'donation' => \Route::input('donation'),
            'just_donated' => \Session::get('just_donated', false),
            'just_subscribed' => \Session::get('just_subscribed', false),
            'just_cancelled' => \Session::get('just_cancelled', false)
        ]);
    }

    public function postStripeIncoming()
    {
        \Stripe::setApiKey(\Config::get('stripe.secret'));
        $event = json_decode(file_get_contents('php://input'));
        //\Stripe_Event::retrieve($event->id); // Validate event

        if ($event->type !== 'invoice.payment_succeeded') return 'Incorrect event type.';

        $invoice = $event->data->object;
        $previous_customer_id = $invoice->customer;

        $otherDonation = Models\Donation::where('transaction_subscription_id', '=', $previous_customer_id)->first();
        $user = [
            'first_name' => $otherDonation->first_name,
            'last_name' => $otherDonation->last_name,
            'email' => $otherDonation->email,
            'amount' => $otherDonation->amount,
            'is_recurring' => false,
            'is_anonymous' => $otherDonation->is_anonymous,
            'for' => $otherDonation->for
        ];

        $donation = $this->createDonationRecord('stripe', $invoice->charge, $previous_customer_id, $user);
        try {
            $this->mailDonationReceipt($donation, true);
        } catch (\Exception $ex) {}
    }

    public function postCancelSubscription()
    {
        $donation = \Route::input('donation');

        \Stripe::setApiKey(\Config::get('stripe.secret'));
        $customer = \Stripe_Customer::retrieve($donation->transaction_subscription_id);
        $customer->delete();

        // Mark all donations as having their subscription cancelled
        $previousDonations = Models\Donation
            ::where('transaction_subscription_id', '=', $donation->transaction_subscription_id)->get();
        foreach ($previousDonations as $previousDonation) {
            $previousDonation->cancelled_at = Carbon::now();
            $previousDonation->save();
        }

        \Session::flash('just_cancelled', true);
        return \Redirect::to('/donate/receipt/'.$donation->id);
    }

    // ====== STRIPE ======

    public function stripeCheckoutRecurring()
    {
        $requirements_check = $this->containsAllRequired(['stripe_token']);
        if (!$requirements_check->success) {
            return $this->makeDonationPage($requirements_check->errors);
        }

        $user = $this->getDonationInfo();

        // Set up the payment profile and start collecting monthly donations
        \Stripe::setApiKey(\Config::get('stripe.secret'));

        try {
            // Get a plan for the recurring billing
            $plan = 'donation_monthly_'.$user['amount'];
            try {
                \Stripe_Plan::retrieve($plan);
            } catch (\Stripe_Error $e) {
                \Stripe_Plan::create([
                    "amount" => $user['amount'] * 100, // in cents
                    "currency" => "usd",
                    "interval" => "month",
                    "id" => $plan,
                    "name" => '$'.$user['amount'].' monthly donation'
                ]);
            }

            // Create a subscription
            $nextBill = Carbon::now()->addMonth();
            $cust = \Stripe_Customer::create([
                'description' => '$'.$user['amount'].'/mo donation for '.$user['first_name'].' '.$user['last_name'],
                'source' => $user['stripe_token'],
                'plan' => $plan,
                'email' => $user['email'],
                'trial_end' => $nextBill->timestamp
            ]);

            // Create the first charge
            $charge = \Stripe_Charge::create([
                "amount" => $user['amount'] * 100, // in cents
                "currency" => "usd",
                "customer" => $cust,
                "description" => 'Online donation',
                "statement_description" => "DONATION"
            ]);

        } catch (\Stripe_CardError $e) {
            return $this->makeDonationPage(['Your card was declined.']);
        } catch (\Exception $e) {
            return $this->makeDonationPage(['Sorry, our payment gateway reported an error. Please try again. Details:', $e->getMessage()]);
        }

        // Create the transaction record
        try {
            $donation_record = $this->createDonationRecord('stripe', $charge->id, $cust->id);
        } catch (\Exception $ex) {
            $charge->refunds->create();
            return $this->makeDonationPage(["Something went wrong on our side; we're looking into it. Your card was not charged."]);
        }

        // Try to track events and send the email
        $this->optionalStep(function() {
            $this->trackDonateEvents();
        });
        $this->optionalStep(function() use ($donation_record) {
            $this->mailDonationReceipt($donation_record);
        });

        // Redirect to the transaction complete page
        \Session::flash('just_subscribed', true);
        return \Redirect::to('/donate/receipt/'.$donation_record->id);
    }

    /**
     * Processes the Stripe transaction and redirects the user to the receipt page.
     */
    public function stripeCheckoutOneTime()
    {
        return $this->makeDonationPage(['Your card was declined.']);
        $requirements_check = $this->containsAllRequired(['stripe_token']);
        if (!$requirements_check->success) {
            return $this->makeDonationPage($requirements_check->errors);
        }

        $user = $this->getDonationInfo();

        // Process the Stripe transaction
        \Stripe::setApiKey(\Config::get('stripe.secret'));

        try {
            $charge = \Stripe_Charge::create([
                "amount" => $user['amount'] * 100, // in cents
                "currency" => "usd",
                "card"  => $user['stripe_token'],<commit_msg>Allow donations again, because Stripe Radar launched<commit_after><?php
namespace StudentRND\Http\Controllers;

use \Carbon\Carbon;
use \StudentRND\Models;

class DonateController extends \StudentRND\Http\Controller {
    private $donation_info;

    public function getIndex()
    {
        if (\Input::has('utm_campaign')) {
            \Session::set('donate_campaign', \Input::get('utm_campaign'));
        }
        return $this->makeDonationPage();
    }

    public function postIndex()
    {
        if (\Input::get('payment_method') === 'stripe' && \Input::get('frequency') === 'monthly') {
            return $this->stripeCheckoutRecurring();
        } else if (\Input::get('payment_method') === 'stripe' && \Input::get('frequency') === 'onetime') {
            return $this->stripeCheckoutOneTime();
        } else if (\Input::get('payment_method') === 'dwolla' && \Input::get('frequency') !== 'monthly') {
            return $this->dwollaCheckout();
        } else {
            return $this->makeDonationPage();
        }
    }

    public function getReceipt()
    {
        return \View::make('pages/donate/receipt', [
            'donation' => \Route::input('donation'),
            'just_donated' => \Session::get('just_donated', false),
            'just_subscribed' => \Session::get('just_subscribed', false),
            'just_cancelled' => \Session::get('just_cancelled', false)
        ]);
    }

    public function postStripeIncoming()
    {
        \Stripe::setApiKey(\Config::get('stripe.secret'));
        $event = json_decode(file_get_contents('php://input'));
        //\Stripe_Event::retrieve($event->id); // Validate event

        if ($event->type !== 'invoice.payment_succeeded') return 'Incorrect event type.';

        $invoice = $event->data->object;
        $previous_customer_id = $invoice->customer;

        $otherDonation = Models\Donation::where('transaction_subscription_id', '=', $previous_customer_id)->first();
        $user = [
            'first_name' => $otherDonation->first_name,
            'last_name' => $otherDonation->last_name,
            'email' => $otherDonation->email,
            'amount' => $otherDonation->amount,
            'is_recurring' => false,
            'is_anonymous' => $otherDonation->is_anonymous,
            'for' => $otherDonation->for
        ];

        $donation = $this->createDonationRecord('stripe', $invoice->charge, $previous_customer_id, $user);
        try {
            $this->mailDonationReceipt($donation, true);
        } catch (\Exception $ex) {}
    }

    public function postCancelSubscription()
    {
        $donation = \Route::input('donation');

        \Stripe::setApiKey(\Config::get('stripe.secret'));
        $customer = \Stripe_Customer::retrieve($donation->transaction_subscription_id);
        $customer->delete();

        // Mark all donations as having their subscription cancelled
        $previousDonations = Models\Donation
            ::where('transaction_subscription_id', '=', $donation->transaction_subscription_id)->get();
        foreach ($previousDonations as $previousDonation) {
            $previousDonation->cancelled_at = Carbon::now();
            $previousDonation->save();
        }

        \Session::flash('just_cancelled', true);
        return \Redirect::to('/donate/receipt/'.$donation->id);
    }

    // ====== STRIPE ======

    public function stripeCheckoutRecurring()
    {
        $requirements_check = $this->containsAllRequired(['stripe_token']);
        if (!$requirements_check->success) {
            return $this->makeDonationPage($requirements_check->errors);
        }

        $user = $this->getDonationInfo();

        // Set up the payment profile and start collecting monthly donations
        \Stripe::setApiKey(\Config::get('stripe.secret'));

        try {
            // Get a plan for the recurring billing
            $plan = 'donation_monthly_'.$user['amount'];
            try {
                \Stripe_Plan::retrieve($plan);
            } catch (\Stripe_Error $e) {
                \Stripe_Plan::create([
                    "amount" => $user['amount'] * 100, // in cents
                    "currency" => "usd",
                    "interval" => "month",
                    "id" => $plan,
                    "name" => '$'.$user['amount'].' monthly donation'
                ]);
            }

            // Create a subscription
            $nextBill = Carbon::now()->addMonth();
            $cust = \Stripe_Customer::create([
                'description' => '$'.$user['amount'].'/mo donation for '.$user['first_name'].' '.$user['last_name'],
                'source' => $user['stripe_token'],
                'plan' => $plan,
                'email' => $user['email'],
                'trial_end' => $nextBill->timestamp
            ]);

            // Create the first charge
            $charge = \Stripe_Charge::create([
                "amount" => $user['amount'] * 100, // in cents
                "currency" => "usd",
                "customer" => $cust,
                "description" => 'Online donation',
                "statement_description" => "DONATION"
            ]);

        } catch (\Stripe_CardError $e) {
            return $this->makeDonationPage(['Your card was declined.']);
        } catch (\Exception $e) {
            return $this->makeDonationPage(['Sorry, our payment gateway reported an error. Please try again. Details:', $e->getMessage()]);
        }

        // Create the transaction record
        try {
            $donation_record = $this->createDonationRecord('stripe', $charge->id, $cust->id);
        } catch (\Exception $ex) {
            $charge->refunds->create();
            return $this->makeDonationPage(["Something went wrong on our side; we're looking into it. Your card was not charged."]);
        }

        // Try to track events and send the email
        $this->optionalStep(function() {
            $this->trackDonateEvents();
        });
        $this->optionalStep(function() use ($donation_record) {
            $this->mailDonationReceipt($donation_record);
        });

        // Redirect to the transaction complete page
        \Session::flash('just_subscribed', true);
        return \Redirect::to('/donate/receipt/'.$donation_record->id);
    }

    /**
     * Processes the Stripe transaction and redirects the user to the receipt page.
     */
    public function stripeCheckoutOneTime()
    {
        $requirements_check = $this->containsAllRequired(['stripe_token']);
        if (!$requirements_check->success) {
            return $this->makeDonationPage($requirements_check->errors);
        }

        $user = $this->getDonationInfo();

        // Process the Stripe transaction
        \Stripe::setApiKey(\Config::get('stripe.secret'));

        try {
            $charge = \Stripe_Charge::create([
                "amount" => $user['amount'] * 100, // in cents
                "currency" => "usd",
                "card"  => $user['stripe_token'],
{'fraction_non_alphanumeric': 0.1574814391776128, 'fraction_numerical': 0.0012849800114220445, 'mean_word_length': 2.242824074074074, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 168, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5887864', 'n_tokens_mistral': 4021, 'n_tokens_neox': 3862, 'n_words': 730}