<?php
session_start();

if (!isset($_SESSION['phoneNumber']) and !isset($_SESSION['name']) and !isset($_SESSION['logged_in'])) {
  header("location:login.php");
}


include 'includes/db_connection.php';
include 'includes/functions.php';

if(!isset($_GET['id']) and !isset($_GET['link'])){
	header("location:login.php");
}

if (isset($_GET['id']) and isset($_GET['link'])) {

	$phoneNumber = $_SESSION['phoneNumber'];
	$app_id = $_GET['id'];
	$link = $_GET['link'];

	// get information about the app , theme  , ringtone by the id 

	$app_query  = "SELECT * FROM `app_store` WHERE `app_id` = '$app_id' ";
	$app_result = mysql_query($app_query);

	$app_store_row = mysql_fetch_array($app_result);

	// sotre the cost 
	$app_cost = $app_store_row['App_Cost'] ;


	/*
	check if the user have enough credit if have credit continue and 
	discount from the credit
	*/


	$query = "SELECT * FROM `user_information` WHERE `Cus_num` = '$phoneNumber'";
	$result = mysql_query($query);
	$row = mysql_fetch_array($result);
	$user_credit = $row['Credit'] ;
	
	if ($user_credit >= $app_cost) {
	    $user_new_credit = $user_credit - $app_cost ;

	    $query = "UPDATE `user_information` SET `Credit`='$user_new_credit'  WHERE `Cus_num` = '$phoneNumber'";
	    $result = mysql_query($query);

	    if ($result) {
	    	header('Content-Type: '. 'audio/mpeg');
	    	header('Content-Type: application/octet-stream');
	    	header("Content-disposition: attachment; filename={$link}");
	    	readfile($link);
	    	
	    	header("location:$link");



	    }
	    


	} else {
		header("location:check_credit.php?message=You do not have enough credit to download this file");
	}
	


} 

?>